Tru*_*gDQ 1 javascript for-loop async-await
有人可以帮我解释为什么它会这样吗?
据我所知,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');Run Code Online (Sandbox Code Playgroud)
为什么?
谢谢!
尝试使用for (const id of ids) {. 如果没有const或let,您将id在全局范围内进行定义。
function sleep(time) {
return new Promise((r) => setTimeout(r, time));
}
async function test(target) {
const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target];
for (const id of ids) {
console.log('X.', target, id);
await sleep(1);
console.log('Y.', target, id);
}
}
test('a');
test('b');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
402 次 |
| 最近记录: |