0

I am using promise code especially using Promise.all() In one of the function I called reject state, so once reject(failure) state executed, it will catch the error message and the rest of the promises should not be executed. This is the rule in promise. But in my code, I called the reject state. Catch function catches the error message. Ok fine. But again control goes to other promises and printing the log statements in my code. Can anyone explain why?

var p1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    console.log("One dude");
    resolve("one");
  }, 3000);
});

var p2 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject("TWO");
  }, 1000);
});

var p3 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    console.log("Three dude");
    resolve("Three");
  }, 4000);
});


Promise.all([p1, p2, p3]).then(function(msg) {
  console.log(msg);
}).catch(function(err) {
  return console.log(err);
});

I'm getting the output:

TWO
One dude
Three dude


I'm expecting output
TWO
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Not sure what you read and where, but the only code that is not executed when a promise is rejected is that in the fulfillment handlers chained to it somewhere. In your case, that is `console.log(msg);`. Rejecting a promise does not affect other independent code from doing anything. – Bergi Sep 03 '18 at 14:15
  • "one dude" and "three dude" is console logged before a promise is returned so its obvious it will be printed – wrangler Sep 03 '18 at 14:24
  • 1
    Possible duplicate of [Handling errors in Promise.all](https://stackoverflow.com/questions/30362733/handling-errors-in-promise-all) – ponury-kostek Sep 03 '18 at 15:02

1 Answers1

0

Your three promisified setTimeouts are independent of each other.

The fact that one rejects has no bearing on the two that resolve. Each of the three promise constructors will execute regardless of what goes on in any of the others, and will do so whether or not the promises are aggregated with Promise.all().

Aggregation with Promise.all() looks at the eventual settlement of the promises without affecting the (typically asynchronous) activities that led to their settlement.

Taking all that into account (and the time values passed to the setTimeouts), it should (I hope) be no surprise that you see :

  • TWO (after 1 second)
  • One dude (after 3 seconds)
  • Three dude (after 4 seconds)
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44