7 Jan, 2017
function runInParallel (input) {
let keys = []
let promises = []
for (let key in input) {
keys.push(key)
promises.push(input[key])
}
return Promise.all(promises).then((resolved) => {
let output = {}
for (let i = 0; i < resolved.length; i++) {
output[keys[i]] = resolved[i]
}
return output
})
}
Example:
runInParallel ({
one: Promise.resolve('one'),
two: Promise.resolve('two'),
}).then((obj) => {
console.log(obj);
})
Gives:
{one: "one", two: "two"}
Be aware that if any promise fails, the Promise.all()
call fails fast, so the catch()
callback will only contain the one rejected promise, and won't wait for the other promises to settle.
Copyright James Gardner 1996-2020 All Rights Reserved. Admin.