Skip to content

Instantly share code, notes, and snippets.

@paulwib
Created November 28, 2016 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulwib/9cfcde16ee2be26a4f8e1fdeaa2a5bb6 to your computer and use it in GitHub Desktop.
Save paulwib/9cfcde16ee2be26a4f8e1fdeaa2a5bb6 to your computer and use it in GitHub Desktop.
Handling mixed success/fail promises
/**
* You have 2 promises either of which may fail or succed.
*
* You want to run a handler after all have failed or succeeded and have access to the result of each promise.
*
* How?
*/
const Promise = require('bluebird');
var fail = n => new Promise((resolve, reject) => setTimeout(function() { reject('fail!') }, n*100));
var pass = n => new Promise((resolve, reject) => setTimeout(function() { resolve('pass!') }, n*100));
// .all() fires the catch() if one fails
Promise.all([fail(1), pass(1)])
.then(results => console.log('1. all(fail, pass).then:', results))
.catch(results => console.log('1. all(fail, pass).catch:', results));
// .any() fires the then() if one succeeds, but you won't see the results of the failure
Promise.any([fail(2), pass(2)])
.then(results => console.log('2. any(fail, pass).then:', results))
.catch(results => console.log('2. any(fail, pass).catch:', results));
// .any() with 2 failures fires the catch, as nothing succeeded
Promise.any([fail(3), fail(3)])
.then(results => console.log('3. any(fail, fail).then:', results))
.catch(results => console.log('3. any(fail, fail).catch:', results));
// .finally() always fires, but doesn't have access to any data
Promise.all([fail(4), pass(4)])
.catch(error => {})
.finally(results => console.log('4. all(fail, pass).finally:', results));
// Answer 1:
// Add a .catch() to all - you'll need to deal with undefined values
Promise.all([fail(5), pass(5)].map(p => p.catch(() => new Error('fail!'))))
.then(results => console.log('5. all(fail.catch(), pass.catch()).then:', results));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment