【发布时间】:2020-06-14 23:43:39
【问题描述】:
当你运行这段代码时
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
对于带有 then 链的简单 Promise 也是如此。
我确实理解为什么 setTimeout 在最后(它是一个宏任务,宏任务必须等待微任务)。
但是 Promise 和 then 都是微任务。那么问题来了,为什么有多个 promise,它们各自的 then 不是粘在一起而是交织在一起的呢?
如我所料,输出如下:
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
【问题讨论】:
-
除了
setTimeout,这里没有异步代码。将async/await扔在某物前面并不会隐含地使其异步 -
嗯,这基本上是一个承诺。如果你用 then 链在 promise 中重写它,你会得到相同的结果。
-
因为这就是异步函数的作用——您可以同时运行多个异步函数。如果您想要提供的信息,您需要
.then链接您的第一个调用,如first().then(...)或者您需要在函数前面放置适当的await。 -
"对于带有 then 链的简单 Promise 也是如此。" - 你能告诉我们你的代码吗?因为这对我有用:
first().then(() => second()) -
我想你会在这里的描述部分找到答案~developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript promise async-await