【发布时间】:2021-10-18 12:42:51
【问题描述】:
有人可以帮我解释一下为什么会这样吗?
据我所知,在这种情况下,添加 await sleep(1) 行不会影响代码流。但是,确实如此。
function sleep(time) {
return new Promise((r) => setTimeout(r, time));
}
async function test(target) {
const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target];
for (id of ids) {
console.log('X.', target, id);
// await sleep(1);
console.log('Y.', target, id);
}
}
test('a');
test('b');
为什么?
谢谢!
【问题讨论】:
-
能否将这两个示例都包含在Stack Snippets 中,这样更容易调试。请参阅Why you shouldn't upload images of code 了解更多信息
-
因为你应该
await test('a'); await test('b');。您当前正在同时运行两个异步操作。此外,id是一个全局变量,因此两个操作同时重用和覆盖同一个变量。难怪你得到一个混乱的输出:) -
for(id of使id成为全局,使用for(const id of使其成为 for 循环的本地
标签: javascript for-loop async-await