Created
October 19, 2017 18:49
-
-
Save dynajoe/2d949a8d3018e0e59996ea3dc75f1148 to your computer and use it in GitHub Desktop.
Example of all settled promises
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
// This will always return a promise that completes when all promises have completed | |
// because we're turning errors into successful promises (because .catch does not throw an error) | |
var allSettled = (promises) => { | |
return Promise.all(promises.map(p => { | |
return p.then(result => { | |
return { result: result, error: null } | |
}) | |
.catch(error => { | |
return { result: null, error: error } | |
}) | |
})) | |
} | |
// if you still want to wait for all results to complete AND have a failed promise this might be how you do it | |
var allSettledWithFailure = (promises) => { | |
var all_promises = Promise.all(promises.map(p => { | |
return p.then(result => { | |
return { result: result, error: null } | |
}) | |
.catch(error => { | |
return { result: null, error: error } | |
}) | |
})) | |
.then(results => { | |
if (results.find(r => r.error !== null)) { | |
return Promise.reject(results) | |
} else { | |
return Promise.resolve(results) | |
// return results <-- this is the same as above except that typescript would complain if the return types didn't match (Promise). | |
} | |
}) | |
} | |
// Usage: | |
// This will show kicking off a couple requests that finish at different times. | |
// Note "All done" will have a timestamp greater than or equal to all responses to show it waits for everything to complete. | |
var start = Date.now() | |
var timeSinceStart = () => { | |
return Date.now() - start | |
} | |
var RequestPromise = { | |
get: () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() > 0.5) { | |
reject(new Error('ERROR! ' + timeSinceStart())) | |
} else { | |
resolve('Data: ' + timeSinceStart()) | |
} | |
}, Math.random() * 3000) | |
}) | |
} | |
} // for copy paste usage | |
var request_1 = RequestPromise.get('https://google.com') | |
var request_2 = RequestPromise.get('https://google.com') | |
var request_3 = RequestPromise.get('https://google.com') | |
var request_4 = RequestPromise.get('https://google.com') | |
allSettled([ | |
request_1, | |
request_2, | |
request_3, | |
request_4, | |
]) | |
.then(results => { | |
console.log('All done: ' + timeSinceStart() + ' ' + JSON.stringify(results)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment