1

When I execute the below Javascript promise.all() code I get the output as

hi
50

But is what I was expecting the output to be

50
hi

Can some one please explain me why "Hi" appeared first and then 50

Below is the code

let p1 = Promise.reject(50);
let p2 = true;
let p3 = new Promise((resolve, reject) => {
  console.log("hi")
  setTimeout(() => reject("hey"), 0);
});
Promise.all([p1, p2, p3])
  .then(values =>  console.log(values))
  .catch(err => console.log(err));
Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33

1 Answers1

3

The callback you pass to new Promise will run synchronously, immediately, at the point you call new Promise. hi not only logs before the timeout, but also before you even call Promise.all.

The setTimeout(() => reject("hey"), 0); callback runs much, much later - only after that callback runs, and the Promise rejects, does the .catch get entered into and log the reject value.

In order for the logged values to be 50 hi, you'd need to log hi

(1) after the reject call

(2) after another microtask (to give time for the .catch to run)

let p1 = Promise.reject(50);
let p2 = true;
let p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("hey");
    // queue microtask
    Promise.resolve().then(() => {
      console.log("hi")
    });
  }, 0);
});
Promise.all([p1, p2, p3])
  .then(values =>  console.log(values))
  .catch(err => console.log(err));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320