Last active
March 8, 2022 18:37
-
-
Save sakiraykurt/ec5b6202839ccc3efb083a5056ced5b9 to your computer and use it in GitHub Desktop.
Run/Call multiple async/promise functions with parameters in parallel
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
/** | |
* Run multiple async/promise functions with parameters in parallel | |
* @param {[[Promise, ...any]]} promises | |
* @returns {Promise<any[]>} values | errors | |
*/ | |
function promiseAll(...promises) { | |
return new Promise((resolve, reject) => { | |
let values = []; let errors = []; | |
function check() { | |
if (values.length + errors.length === promises.length) { | |
if (errors.length > 0) | |
reject(errors); | |
else | |
resolve(values) | |
} | |
} | |
function vback(value) { | |
values.push(value); | |
check(); | |
} | |
function eback(error) { | |
errors.push(error); | |
check(); | |
} | |
promises.forEach(params => params.shift()(...params).then(vback, eback)); | |
}); | |
} | |
// :::USAGE::: | |
// function a() { | |
// return new Promise((resolve, reject) => { | |
// setTimeout(() => { | |
// resolve("hi"); | |
// }, 1000); | |
// }); | |
// } | |
// function b(pId) { | |
// return new Promise((resolve, reject) => { | |
// setTimeout(() => { | |
// resolve([pId, "hello", "world"]); | |
// }, 500); | |
// }); | |
// } | |
// async function c(pId, any) { | |
// const promise = new Promise(resolve => { | |
// setTimeout(() => resolve([pId, any]), 250); | |
// }); | |
// return await promise; | |
// } | |
// (async () => { | |
// try { | |
// console.log(await promiseAll([a], [b, "p1"], [c, "p2", "hey"])); | |
// } catch (errors) { | |
// console.error(errors); | |
// } | |
// })(); | |
// promiseAll([a], [b, "p1"], [c, "p2", "hey"]).then(values => { | |
// console.log(values); | |
// }).catch(errors => { | |
// console.error(errors); | |
// }); | |
// | |
// log: [ [ 'p2', 'hey' ], [ 'p1', 'hello', 'world' ], 'hi' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment