2

async function a1() {
  console.log(1);
  const data = await a2();
  // const data = await new Promise(res=> res()).then(()=>{console.log(2)});
  console.log(5);
}

async function a2() {
  return new Promise(res=> res()).then(()=>{console.log(2)})
}

a1();

new Promise(function(res) {
  res()
}).then(() => { console.log(3) })
  .then(() => { console.log(4) })
  .then(() => { console.log(6) })

async function a1() {
  console.log(1);
  const data = await new Promise(res=> res()).then(()=>{console.log(2)});
  console.log(5);
}

a1();

new Promise(function(res) {
  res()
}).then(() => { console.log(3) })
  .then(() => { console.log(4) })
  .then(() => { console.log(6) })

Why does the code will run in different order? (that two data)

await with function will print 1,2,3,4,5,6

await with expression will print 1,2,3,5,4,6

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Zorba
  • 33
  • 3
  • 1
    You shouldn't really rely on the the order promises are completed. The chain `1 -> 2 -> 5` finishes in sequence, as does the chain `3 -> 4 -> 6`. You're guaranteed *that*. But not what happens when you have two chains competing with one another when you've not linked them in any way. – VLAZ Jun 08 '21 at 17:14
  • Your first and your second code snippet are not equivalent in the number of Promises that are created and how they are chained. With a short look they would IMHO be equivalent if you would write `async function a1() { console.log(1); const data = await await new Promise(res=> res()).then(()=>{console.log(2)}); console.log(5); }` (an additional `await` in front of the other `await`) – t.niese Jun 08 '21 at 17:36
  • @Rounin I only partially agree with that. In the shown code, you only have immediate resolving Promises, so there is nothing that depends on IO and only on queuing in the event loop. So if the code is run in the same engine over and over again, the order should always be the same. But that's only true for this kind of arbitrary example. – t.niese Jun 08 '21 at 17:41
  • The order is completely deterministic here. Afaik the difference is, that the async function wraps everything in another Promise. This means the microtask-queue gets one additional run to the end before the `console.log(5)` task can execute, causing it to be one later. As a test, try `const data = await new Promise(res => res(new Promise(res=> res()).then(()=>{console.log(2)})));`. – ASDFGerte Jun 08 '21 at 17:48

0 Answers0