Skip to content

Instantly share code, notes, and snippets.

@tomersh
Last active April 19, 2018 23:59
Show Gist options
  • Save tomersh/96d60f42bdd172ad65b9ec6c40910140 to your computer and use it in GitHub Desktop.
Save tomersh/96d60f42bdd172ad65b9ec6c40910140 to your computer and use it in GitHub Desktop.
Unlike Promise.all(), that will reject when the first promise rejects, the Promise.waitForAll() will never rejects. The method returns a single Promise that resolves when all of the promises in the iterable argument have either resolved or rejects. It returns an array of objects with either a results or error key.
Promise.waitForAll = promises => {
if (!promises || typeof promises[Symbol.iterator] !== 'function') {
return Promise.reject();
}
if (promises.length === 0) {
return Promise.resolve([]);
}
return Promise.all(
promises.map((promise) => {
return new Promise((resolve) => {
promise.then(result => {
resolve({ status: "success", result : result });
}, err => {
resolve({ status: "failure", error : err });
});
});
})
);
}
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
const testFunction = (index) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(index)
}
else {
reject(index);
}
}, getRandomInt(1, 250));
});
}
const promises = [];
for (var i=0; i < 100; i++) {
promises.push(testFunction(i));
}
Promise.waitForAll(promises).then(results => {
console.log(`${results.length} promises ended`);
for (var i=0; i < results.length; i++) {
const result = results[i];
if (result.status === "success") {
console.log(`${i} >> success: ${result.result}`);
}
else {
console.log(`${i} >> failure: ${result.error}`);
}
}
}, err => { console.log(err); } );
@tomersh
Copy link
Author

tomersh commented Jul 31, 2017

@leesh86
Copy link

leesh86 commented Aug 1, 2017

amazing. exactly what i needed. <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment