简体   繁体   English

在 async 函数内的 for 循环中等待给出奇怪的结果

[英]Await inside a for loop inside an async function gives strange result

Can someone help explain to me why is it behave this way?有人可以帮我解释一下为什么它会这样吗?

To the best of my knowledge, adding the await sleep(1) line should not affect the code flow in this case.据我所知,在这种情况下,添加await sleep(1)行不应影响代码流。 However, it does.但是,确实如此。

 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');

前

后

Why?为什么?

Thanks!谢谢!

Try using for (const id of ids) { .尝试使用for (const id of ids) { Without const or let , you're defining id on the global scope.如果没有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');

You're not waiting test('a') to finish.您不是在等待test('a')完成。

When test('b') is reached, test('a') is still running (because it's an async function).当达到test('b')时, test('a')仍在运行(因为它是一个异步函数)。 If you want it to finish before starting the other one use .then() :如果您希望它在开始另一个之前完成,请使用.then()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM