Home > other >  Await inside a for loop inside an async function gives strange result
Await inside a for loop inside an async function gives strange result

Time:10-18

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. 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');
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

before

after

Why?

Thanks!

CodePudding user response:

Try using for (const id of ids) {. Without const or let, you're defining id on the global scope.

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

CodePudding user response:

You're not waiting test('a') to finish.

When test('b') is reached, test('a') is still running (because it's an async function). If you want it to finish before starting the other one use .then():

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