Functions with async / await running out of order

Asked

Viewed 93 times

4

Can anyone explain to me if this is the expected behavior, or if I made a mistake in the code below? The expected behavior (in my understanding) would be to log 1,2,3 in sequence.

let funcao1 = async() => {
  console.log(1)
  await funcao2()
  console.log(3)
}

let funcao2 = async() => {
  setTimeout(() => {
    console.log(2)
  }, 1000);
}

funcao1()

  • 2

    Do it without setTimeout to see, calling the console.log directly that makes it easier to understand. This has nothing to do with async, if do with normal synchronous function call gives in it (will go out of order because of the timeout, which simply "schedule" the call, out of normal flow).

1 answer

8


No, because the Promise implicitly returned by funcao2 is solved soon after the function is called (with a tiny delay due to the way these operations are stacked by JS).

This makes the await do not wait for 2 be printed on the console, which will only be done after 1 second from call to function setTimeout.

If you want 1, 2 and 3 to be printed in order, funcao2 must return a Promise wait for a second of the setTimeout. In that case, a Promise will have to be explicitly returned, which makes the annotation async unnecessary in funcao2. Behold:

async function funcao1() {
  console.log(1);
  await funcao2();
  console.log(3);
}

function funcao2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(2);
      resolve();
    }, 1000);
  });
}

funcao1();

  • 3

    In short, the resolve() which is the basic of the Promises :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.