【问题标题】:Await inside a for loop inside an async function gives strange result在异步函数内的 for 循环中等待会产生奇怪的结果
【发布时间】: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


【解决方案1】:

尝试使用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');

【讨论】:

  • 这很好。如果它仍在发生,那么这可能是答案:stackoverflow.com/questions/23392111/console-log-async-or-sync 如果console.log 是同步的,它永远不会发生,但这不是标准化的。好像你已经证明 console.log 应该被认为是异步的。
  • 谢谢!这正是问题所在!
【解决方案2】:

您没有等待test('a') 完成。

当达到test('b') 时,test('a') 仍在运行(因为它是一个异步函数)。如果您希望它在开始另一个之前完成,请使用 .then():

test('a').then(()=>test('b'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2019-07-02
    相关资源
    最近更新 更多