Currently, I'm grappling with the concepts of job queue and promise resolution in Javascript. While going through Nicholas Zakas' book "Understanding ECMAScript 6", I came across a code snippet regarding Promise.race() that has left me puzzled:
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = Promise.reject(43);
let p3 = new Promise(function(resolve, reject) {
resolve(44);
});
let p4 = Promise.race([p1, p2, p3]);
p4.catch(function(value) {
console.log(value); // 43
});
In this scenario, p4 is rejected due to p2 already being in a rejected state when Promise.race() is invoked. Even though p1 and p3 are fulfilled, their outcomes are disregarded since they happen after p2's rejection.
My understanding is that Promise.race() resolves as soon as one of the provided promises is resolved. However, I am confused about why the book states that promise p1 settles after p2. If we follow the code from top to bottom, p1 comes first, so I would expect it to be settled first. Could this be due to the function wrapping, or is there something about Javascript execution order that I am missing?
Would appreciate it if someone could help clarify this concept for me.