Skip to content

Instantly share code, notes, and snippets.

@shadowcodex
Last active December 7, 2018 16:35
Show Gist options
  • Save shadowcodex/7a8c80b48b90b2e37c7779e51fb7f538 to your computer and use it in GitHub Desktop.
Save shadowcodex/7a8c80b48b90b2e37c7779e51fb7f538 to your computer and use it in GitHub Desktop.
Prevent Promise.all fail fast
const resob = promise => {
return promise.then(result => ({ success: true, result })).catch(error => ({ success: false, error }))
}
const list = getListOfObjectsToHit();
let promises = list.map((value) => {
return resob(someAsyncProcess(value));
})
await Promise.all(promises).then((values) => {
for (let i = 0; i < values.length; i++) {
if(values[i].success) {
// your Async Process succeded.
} else {
// your Async Process failed.
}
}
})

Prevent Promise.all Fail Fast

The default behavior of Promise.all is to fail-fast which means that as soon as one of your promises fails then your entire promise chain stops. This is not always the wanted behavior. For example if you are calling an API endpoint to get data on multiple objects then you want to keep going even if some of them fail. Then you can write your own logic to handle those failures in your Promise.all resolution.

The related code here runs a function called resob or resolve object where it forces a promise to fully resolve with either the result or an error. This allows the Promise.all to continue to run even though that one request failed.

It's a simple but elegant way to get results for all objects even though request #2 of 200 failed.

Enjoy! shadowcodex

@bdeo
Copy link

bdeo commented Aug 24, 2018

I adapted the above resob method to handle callback style methods as well.

const resobCb = (cb, paramArr) => {
  return new Promise((resolve) => {
    cb(...paramArr, (error, result) => {
      if (error) {
        resolve({ success: false, error });
      } else {
        resolve({ success: true, result });
      }
    })
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment