Mar*_*arv 4 javascript node.js promise es6-promise
我正在创建一个模块,它根据收到的配置执行任务.这些任务是异步的,并且正在返回一个promise.目前只有两个任务需要处理,但是如果还有更多的任务要处理,我将遇到一个问题,即确定哪个结果Promise.all()属于哪个任务.
这是我当前代码的快照:
let asyncTasks = [];
let result = {};
if (config.task0) {
asyncTasks.push(task0(param));
}
if (config.task1) {
asyncTasks.push(task1(param));
}
Promise.all(asyncTasks)
.then(results => {
// TODO: There has to be a prettier way to do this..
if (config.task0) {
result.task0 = results[0];
result.task1 = config.task1 ? results[1] : {};
} else if (config.task1) {
result.task0 = {};
result.task1 = results[0];
} else {
result.task0 = {};
result.task1 = {};
}
this.sendResult(result)
});
Run Code Online (Sandbox Code Playgroud)
配置如下所示:
const config = {
task0: true,
task1: true
};
Run Code Online (Sandbox Code Playgroud)
正如代码中所提到的,必须有一种更漂亮,更可扩展的方法来识别哪个结果来自哪个任务,但我无法找到任何有关Promise.all()此问题的信息.
如何Promise.all()解析,如何识别哪个值属于哪个承诺?
Promise.all使用值数组解析,其中数组中的每个值的索引与传递给Promise.all生成该值的原始数组中的Promise的索引相同.
如果您需要更多花哨的东西,您需要自己跟踪它或使用另一个提供此类功能的库(如Bluebird).
除了 之外,确实没有必要使用任何其他东西Promise.all。您遇到困难是因为程序的其他结构(config以及配置键与功能的任意链接)非常混乱。您可能需要考虑完全重构代码
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: {}
// })
Run Code Online (Sandbox Code Playgroud)
注意:我们可以依赖的顺序,results因为我们曾经Object.keys(config)创建 Promise 的输入数组,然后Object.keys(config)再次创建输出对象。
| 归档时间: |
|
| 查看次数: |
1348 次 |
| 最近记录: |