Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active September 27, 2017 15:35
Show Gist options
  • Save catdad/05b1729dc506138b8038eca4d66ed692 to your computer and use it in GitHub Desktop.
Save catdad/05b1729dc506138b8038eca4d66ed692 to your computer and use it in GitHub Desktop.
Promise.all, but wait for all promises to finish

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.

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