Last active
April 19, 2018 23:59
-
-
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.
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
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); } ); |
amazing. exactly what i needed. <3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://repl.it/repls/AngelicPlumTheory