Promise.all
will execute all promises in parallel, and fail whenever any one of the promises fails. This could even include failing synchronously if one is a Promise.reject()
. Instead of doing this, here we want to make sure that all promises finish before we handle the result. We wait for all promises to finish, check their status, and reject or resolve the final promise based on whether any errors were encountered or not.
Last active
September 27, 2017 15:35
-
-
Save catdad/05b1729dc506138b8038eca4d66ed692 to your computer and use it in GitHub Desktop.
Promise.all, but wait for all promises to finish
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
function reflect(obj) { | |
if (!obj.then) { | |
return { ok: true, value: obj }; | |
} | |
return obj | |
.then((value) => { | |
return { ok: true, value }; | |
}) | |
.catch((err) => { | |
return { ok: false, err }; | |
}); | |
} | |
module.exports = function (promiseArr) { | |
return Promise.all(promiseArr.map(reflect)) | |
.then((statuses) => { | |
var error; | |
var values = statuses.map((status) => { | |
if (status.ok) { | |
return status.value; | |
} | |
error = status.err; | |
}); | |
if (error) { | |
return Promise.reject(error); | |
} | |
return values; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment