Last active
October 11, 2018 16:10
-
-
Save crazy4groovy/d93c0d4ab807ef8e94e9906fba7d24fc to your computer and use it in GitHub Desktop.
A strategy to try a list of promises, and then check which ones were resolved (or rejected).
This file contains hidden or 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
var promises = []; | |
var cnt = 0; | |
function makePromises() { | |
console.log('make', Date.now()) | |
promises.length = 0; // clear array | |
promises.push(new Promise((resolve, reject) => setTimeout(resolve, 1000, `Everything OK in Promise ${cnt++}`))); | |
promises.push(new Promise((resolve, reject) => setTimeout(resolve, 2000, `Everything OK in Promise ${cnt++}`))); | |
promises.push(new Promise((resolve, reject) => reject(new Error(`Something went wrong in Promise ${cnt++}`)))); | |
return promises; | |
} | |
function resolveRejectify (promise) { | |
return promise | |
.then(resolved => ({ resolved })) | |
.catch(rejected => ({ rejected })); | |
} | |
function checkResults(promiseResults) { | |
console.log('check', Date.now()) | |
promiseResults.forEach((result) => { | |
if (result.rejected) console.error(`ERR: ${result.rejected.message}`); | |
else console.log(result.resolved); | |
}); | |
} | |
Promise.all(makePromises().map(resolveRejectify)) | |
.then(checkResults) | |
.then( | |
Promise.all(makePromises().map(resolveRejectify)) | |
.then(checkResults) | |
).then( | |
Promise.all(makePromises().map(resolveRejectify)) | |
.then(checkResults) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
credit: https://nmaggioni.xyz/2016/10/13/Avoiding-Promise-all-fail-fast-behavior/