Can I ensure the execution queue of two parallel promises?

Today I have met a boring interview question, and can I ensure that two parallel promises like the following snippet should execute according to the order? It seems that V8 has inserted the microtask of printing 4 between 3 and 5.

Promise.resolve()
  .then(() => {
    console.log(0);
    return Promise.resolve(4);
  }).then(console.log);
  
Promise.resolve().then(() => { console.log(1) })
  .then(() => { console.log(2) })
  .then(() => { console.log(3) })
  .then(() => { console.log(5) })
  .then(() => { console.log(6) });

// => [INFO] 0
// => [INFO] 1
// => [INFO] 2
// => [INFO] 3
// => [INFO] 4
// => [INFO] 5
// => [INFO] 6

"boring interview question"? I'd say a completely ridiculous question. I can see 10 promises in that example. Anyone writing asynchronous code relying on a particular order of execution, without enforcing that order with proper await/then sequencing, is going to shoot someone in the foot, sooner or later.

3 Likes

:rofl:

1 Like

Absolutely! If 'N' needs to happen after 'N-1' then it should await that task resolving.

If someone relies on the implicit behaviour, and of course the code can not be maintained.

1 Like

Reminds me of something someone was asking me about not too long ago:

async function loop () {
  for (let x of [1,2,3,4,5]) {
    console.log(await x)
  }
}
async function loop2 () {
  for await (let x of [1,2,3,4,5]) {
    console.log(x + '.2')
  }
}

loop()
loop2()

Result:

1
2
1.2
3
4
2.2
5
3.2
4.2
5.2