1

I am trying to run several promises where there is a potential that one might fail. In the case that one does fail, how do I find out which one failed and still be able to access the result of promises that did not fail?

Right now, I am using Promise.all, but if any of the promises fail, Promise.all automatically goes into the catch error block so I can't access anything from my .then block so I can't access any of the successful promise results. Can someone help?

My fiddle: https://jsfiddle.net/9u2nL7zj/

My code:

let promise1 = new Promise((resolve, reject) => {
  console.log('-uno-')
  resolve('-promise 1 success')
})

let promise2 = new Promise((resolve, reject) => {
  console.log('-dos-')
  reject('-promise 2 fail')
})

let promise3 = new Promise((resolve, reject) => {
  console.log('-tres-')
  reject('-promise 3 fail')
})


let promise4 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('-cuatro-')
    resolve('-promise 4 success-')
  }, 3000)
})


Promise.all([promise1, promise2, promise3, promise4]).then((res) => {
  console.log('--done--', res)
}).catch((err) => {
  console.log('--err--', err)
})
Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • 1
    If I understand correctly you want to access results of all resolved Promises even if there is a failed one (including those that might resolve after the failed one, or else it would be... complicated) -- so essentially you want to wait for all, right? To me it sounds very much like [that question](http://stackoverflow.com/q/31424561/6730571). `Promise.all` means all must resolve. What you want is something like [Q](https://github.com/kriskowal/q/wiki/API-Reference#promiseallsettled)'s `Promise.allSettled`, but that is not standard, it's a library. – Hugues M. May 06 '17 at 18:27

1 Answers1

0

It doesn't seem like Promise.all is the best way to go about this problem. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all):

If any of the passed-in promises reject, Promise.all immediately rejects with the value of the promise that rejected, whether or not the other promises have resolved.

So Promise.all() is for cases when you need every promise to resolve. Is there a reason you need them all to resolve together. If not, it would be best to just give each promise it's own .then() and .catch() blocks.

Andrew
  • 19
  • 3