Angelki
Angelki

Reputation: 103

execution order of the code below and why?

Mainly the order of “promise2” and “async1 end”. I don't know why.

async function async2() {
  console.log("async2");
}
new Promise(resolve => {
  resolve(async2());
}).then(() => {
  console.log("async1 end");
});

new Promise(function(resolve) {
  console.log("promise1");
  resolve();
}).then(function() {
  console.log("promise2");
});

Upvotes: 0

Views: 47

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

 resolve(async2());

is briefly the same as:

resolve(Promise.resolve())

So it creates a Promise that will resolve, and passes that to the resolution of another promise. As Promises get flattened (resolving a promise with a promise, will make the outer promise wait for the inner), your examples could be simplified to:

 Promise.resolve("first").then(console.log);

 Promise.resolve("second")
   .then(it => it) 
   .then(console.log);

Now resolving a Promise is guaranteed to be asynchronous, so even if you resolve it synchronously like in your case, the .then callbacks will only be called after 1 tick. Now the first one will log after one tick, the second one will also resolve after one tick, then the chained Promise will resolve which will then wait another tick till the third one is done.

Therefore “promise2” will be logged after one tick, and “async1 end” after two ticks.


Nevertheless you should not rely on the execution order of promises.

Upvotes: 1

Related Questions