How to identify results in Promise.all()
Promise.all
resolves with an array of values, where each value's index in the array is the same as the index of the Promise in the original array passed to Promise.all
that generated that value.
If you need anything more fancy you'll need to keep track of it yourself or use another library that offers such functionality (like Bluebird).
There's really no need to use anything other than Promise.all
. You're experiencing difficulty because the other structure of your program (config
, and arbitrary link of config key to function) is pretty messy. You might want to consider restructuring the code altogether
const config = {
task0: true,
task1: true,
task2: false
}
// tasks share same keys as config variables
const tasks = {
task0: function(...) { ... },
task1: function(...) { ... },
task2: function(...) { ... }
}
// tasks to run per config specification
let asyncTasks = Object.keys(config).map(prop =>
config[prop] ? tasks[prop] : Promise.resolve(null))
// normal Promise.all call
// map/reduce results to a single object
Promise.all(asyncTasks)
.then(results => {
return Object.keys(config).reduce((acc, task, i) => {
if (config[task])
return Object.assign(acc, { [prop]: results[i] })
else
return Object.assign(acc, { [prop]: {} })
}, {})
})
// => Promise({
// task0: <task0 result>,
// task1: <task1 result>,
// task2: {}
// })
Note: we can depend on the order of results
because we used Object.keys(config)
to create the input array of promises and Object.keys(config)
again to create the output object.