如果我直接等待
Promise
,执行顺序似乎是合理的。async
函数,即没有其他任何更改,顺序就会完全改变。看了一些资料,我想我明白了。
// await Promise directly, the output will be
// "calling" 1 "resolved" 4 2 5 3 6
function f() {
return new Promise(resolve => {
resolve('resolved');
});
}
async function test() {
console.log('calling');
const result = await f();
console.log(result);
}
Promise.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3))
test();
Promise.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6))
case2 -> 改为异步函数
// "calling" 1 4 2 5 3 "resolved" 6
async function f() {
return new Promise(resolve => {
resolve('resolved');
});
}
async function test() {
console.log('calling');
const result = await f();
console.log(result);
}
// [then1] 'calling' [then1 p.then then4]
// 1 4 [then2 resolve-p2 then5]
// 2 5 [then3 then-resolved then6]
// 3 'resolved' 6
Promise.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3))
test();
Promise.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6))