This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function executeAllPromises(promises) { | |
// Wrap all Promises in a Promise that will always "resolve" | |
var resolvingPromises = promises.map(function(promise) { | |
return new Promise(function(resolve, reject) { | |
var payload = new Array(2); | |
promise.then(function(result) { | |
payload[0] = result; | |
}) | |
.catch(function(error) { | |
payload[1] = error; | |
}) | |
.then(function() { | |
/* | |
* The wrapped Promise returns an array: | |
* The first position in the array holds the result (if any) | |
* The second position in the array holds the error (if any) | |
*/ | |
resolve(payload); | |
}); | |
}); | |
}); | |
var errors = []; | |
var results = []; | |
// Execute all wrapped Promises | |
return Promise.all(resolvingPromises) | |
.then(function(items) { | |
items.forEach(function(payload) { | |
if (payload[1]) { | |
errors.push(payload[1]); | |
} else { | |
results.push(payload[0]); | |
} | |
}); | |
return { | |
errors: errors, | |
results: results | |
}; | |
}); | |
} | |
var myPromises = [ | |
Promise.resolve(1), | |
Promise.resolve(2), | |
Promise.reject(new Error('3')), | |
Promise.resolve(4), | |
Promise.reject(new Error('5')) | |
]; | |
executeAllPromises(myPromises).then(function(items) { | |
console.log(`Executed all ${myPromises.length} Promises:`); | |
console.log(`— ${items.results.length} Promises were successful.`, items.results); | |
console.log(`— ${items.errors.length} Promises failed.`, items.errors); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment