【发布时间】:2020-06-07 13:13:13
【问题描述】:
我试图在 JavaScript 中可视化 for...await 循环的同步性。
似乎在async 生成器函数中both yield 和await 将停止进度并提示微任务的继续。
换句话说:在这种情况下,产生始终是异步的,即使您不使用 await 关键字。
这是正确的吗? async 生成器函数在 for...await 循环的上下文之外呢?
下面使用then 创建了一个紧密的微任务循环,以尝试查看任务是如何交错的。
function printNums() {
let counter = 0
function go() {
console.log(counter++)
if(counter < 10) Promise.resolve().then(go)
}
Promise.resolve().then(go)
}
printNums()
async function asyncFn() {
console.log('inside asyncFn 1')
await null
console.log('inside asyncFn 2')
}
asyncFn()
const asyncIterable = {
async *[Symbol.asyncIterator]() {
console.log('inside asyncIterable 1')
yield '⛱'
console.log('inside asyncIterable 2')
await null
console.log('inside asyncIterable 3')
yield '????'
yield '????'
}
}
async function printAsyncIterable() {
for await(let z of asyncIterable) {
console.log(z)
}
}
printAsyncIterable()
【问题讨论】:
-
正确,但如您所知,您应该将问题限制为一个问题。
标签: javascript