我试着从谷歌源代码中了解承诺,但没有发现它是如何异步执行代码的。
我对异步函数的理解是,下面的代码可以在它之前的一段时间被解析。
例如:
setTimeout(()=>{console.log("in")}, 5000);
console.log("out");
// output:
// out
// in第二行在第一行之前填充,所以我认为setTimeout是一种异步技术。但请参阅Promise的代码
let p = new Promise((resolve, reject)=>{console.log('in'); resolve(1);});
console.log("out");
//in
//out这个代码块实际上是逐行执行的,如果console.log('in');是一个耗时的操作,那么第二行将被阻塞,直到它被解析为止。
我们通常这样使用Promise:
(new Promise(function1)).then(function2).then(function3)这是否意味着:Promise只是用来保证在function1之后执行function2,它不是一种实现asynchronous的技术,而是一种实现synchronous的方法(function1、function2、function3是连续执行的)。
发布于 2019-03-28 16:59:36
承诺只是描述一个价值的一种方式,这个价值还不存在,但会在稍后到达。您可以将.then处理程序附加到它,以便在发生这种情况时得到通知。
这是否意味着:承诺只是用来承诺在function2之后执行function1?
是的,即使function1异步地返回它的值(通过承诺),function2也只有在该值存在时才会运行。
它不是一种实现‘异步’的技术,而是一种实现‘同步’执行的方法?
不怎么有意思。将已经存在的值封装到承诺中是没有意义的。将将“异步”调用包装为承诺的回调是有意义的。也就是说,承诺本身并不表示它解析为哪个值是在同步或异步管理器中检索的。
function retrieveStuffAsynchronously() {
// direclty returns a Promise, which will then resolve with the retrieved value somewhen:
return new Promise((resolve, reject) => {
// directly executes this, the async action gets started below:
setTimeout(() => { // the first async code, this gets executed somewhen
resolve("the value"); // resolves asynchronously
}, 1000);
});
}
console.log(retrieveStuffAsynchronously()); // does return a promise immeadiately, however that promise is still pending
retrieveStuffAsynchronously().then(console.log);
Sidenote:但是,保证保证异步解决:
const promise = new Promise((resolve, reject)=>{
console.log('one');
resolve('three');
});
promise.then(console.log); // guaranteed to be called asynchronously (not now)
console.log("two");
https://stackoverflow.com/questions/55402935
复制相似问题