在异步函数内的 for 循环内等待会产生奇怪的结果

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)

前

后

为什么?

谢谢!

sle*_*ita 5

尝试使用for (const id of ids) {. 如果没有constlet,您将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)