[英]Order of execution in promises in javascript
我有一个示例程序来了解promises
和async/ await
是如何工作的。 但是我对 Promise 的执行顺序有点困惑。 任何人都可以解释这是如何工作的吗?
//Promise 1
let promiseTest = new Promise((resolve, reject) => {
var k = 0;
for(i=0; i< 1000; i++ ){
k += i;
}
resolve(k);
console.log("Inside promise1")
});
promiseTest.then((res)=> {
console.log('Promise1 result : '+ res);
}).then(() => {
promiseTest2.then((res) => {
console.log(res)
});
}).then(finish)
.catch((err) => {
console.log(err)
});
//Promise 2
let promiseTest2 = new Promise ((resolve, reject) => {
console.log("Inside promise2")
});
function finish(){
console.log("finished promise");
}
为此,我得到的结果为
Inside promise1
Inside promise2
Promise1 result : 499500
finished promise
我还有另一个例子,用 async/await 做同样的事情。 但是按照这个执行顺序是正确的。
//Async await test
async function AsyncTest(){
console.log("Inside async1")
var k = 0;
for(i=0; i< 1000; i++ ){
k += i;
}
console.log('async1 result : '+ k);
const result = await AsyncTest2();
console.log(result)
console.log("finished async");
}
async function AsyncTest2(){
return "Inside async2";
}
AsyncTest();
Inside async1
async1 result : 499500
Inside async2
finished async
谢谢。
如果您在 Promise 上调用.then(cb)
,则会创建一个新的 Promise 并由它返回,它将解析为回调返回的任何内容。 如果那是 Promise 本身,则在链继续之前将等待该 Promise。 在你的情况下,你做了:
promiseTest.then((res)=> {
console.log('Promise1 result : '+ res);
return undefined; // implicit return
}).then(() => {
/* doesnt matter what you do here */
return undefined;
}).then(finish)
您是否将另一个.then
附加到另一个承诺与此承诺链无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.