?为什么有了多重承诺,他们各自的承诺不是粘在一起,而是交织在一起?



当你运行此代码时

setTimeout(function(){
console.log('setTimeout')
},0)
console.log('start');
async function first() {
await console.log('first_resolve');
await console.log('first_then_1');
await console.log('first_then_2');
}
async function second() {
await console.log('second_resolve');
await console.log('second_then_1');
await console.log('second_then_2');
}
first()
second()

Promise.resolve(console.log('third_resolve'))
.then(() => console.log('third_then_1'))
.then(() => console.log('third_then_2'))
Promise.resolve(console.log('fourth_resolve'))
.then(() => console.log('fourth_then_1'))
.then(() => console.log('fourth_then_2'))
console.log('end');

您可以在控制台中得到这个

start
first_resolve
second_resolve
third_resolve
fourth_resolve
end
first_then_1
second_then_1
third_then_1
fourth_then_1
first_then_2
second_then_2
third_then_2
fourth_then_2
setTimeout

对于带有然后链的简单承诺也是如此。

我确实理解为什么setTimeout在最后(这是一个宏任务,宏任务必须等待微任务(。

但承诺和然后都是微任务。那么问题来了,为什么有了多重承诺,它们各自的承诺就没有粘在一起,而是交织在一起呢?

正如我所期望的那样,以下输出:

start
first_resolve
first_then_1
first_then_2
second_resolve
second_then_1
second_then_2
third_resolve
third_then_1
third_then_2
fourth_resolve
fourth_then_1
fourth_then_2
end
setTimeout

仅当按顺序调用两个异步函数firstsecond时,才会预期预期结果。 这可以演示如下...

setTimeout(function(){
console.log('setTimeout')
},0)
console.log('start');
async function first() {
await console.log('first_resolve');
await console.log('first_then_1');
await console.log('first_then_2');
}
async function second() {
await console.log('second_resolve');
await console.log('second_then_1');
await console.log('second_then_2');
}
async function opExperiment() {
await first()
await second()
console.log('end');
}
opExperiment()

编辑

响应OP的编辑。 异步函数之后的两个 promise 代码块遵循相同的规则。 要使这些承诺按顺序运行,它们必须等待或由then()连接。 再次演示...

setTimeout(function() {
console.log('setTimeout')
}, 0)
console.log('start');
async function first() {
await console.log('first_resolve');
await console.log('first_then_1');
await console.log('first_then_2');
}
async function second() {
await console.log('second_resolve');
await console.log('second_then_1');
await console.log('second_then_2');
}
async function opExperiment() {
await first()
await second()
await Promise.resolve(console.log('third_resolve'))
.then(() => console.log('third_then_1'))
.then(() => console.log('third_then_2'))
await Promise.resolve(console.log('fourth_resolve'))
.then(() => console.log('fourth_then_1'))
.then(() => console.log('fourth_then_2'))
console.log('end');
}
opExperiment()

相关内容

  • 没有找到相关文章

最新更新