Tony Dinh
Tony Dinh

Reputation: 6726

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

before

after

Why?

Thanks!

Upvotes: 1

Views: 431

Answers (2)

sleepy_keita
sleepy_keita

Reputation: 1508

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

Upvotes: 5

Roger Miranda Perez
Roger Miranda Perez

Reputation: 112

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

Upvotes: 2

Related Questions