Home > Back-end >  Why Promise.race([Promise.resolve(1), 2]).then(console.log) returns 1 instead of 2?
Why Promise.race([Promise.resolve(1), 2]).then(console.log) returns 1 instead of 2?

Time:09-10

Why does this behavior happen with Promise.race(), that Promise.resolve(1) calculates faster rather than just 2?

Promise.race([Promise.resolve(1), 2]).then(console.log)

CodePudding user response:

From MDN docs

If the iterable contains one or more non-promise value and/or an already settled promise, then Promise.race will settle to the first of these values found in the array

const foreverPendingPromise = Promise.race([]);
const alreadyFulfilledProm = Promise.resolve(100);

const arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"];
const arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(100)];
const p = Promise.race(arr);
const p2 = Promise.race(arr2);

console.log(p);
console.log(p2);
setTimeout(() => {
  console.log("the stack is now empty");
  console.log(p);
  console.log(p2);
});

// logs, in order:
// Promise { <state>: "pending" }
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "fulfilled", <value>: 100 }
// Promise { <state>: "fulfilled", <value>: "non-Promise value" }

CodePudding user response:

Basically, Promise.race and Promise.all implicitly call Promise.resolve on arguments and the 1 just comes before the 2.

This is also true for the values returned from then callbacks, things you await and several other places and the idea was to make it easier to inter-op between promise and non-promise code.

  • Related