我的程序有以下流程:
Promise.resolve(phase_1)
.then(phase_2)
.then(phase_3)
.then(phase_4)
.catch(errorHandler);
但我想要 flow.json 中的各个阶段:
[
"phase_1",
"phase_2",
"phase_3",
"phase_4",
]
但达到相同的结果。可能吗?
我如何尝试:
let returning;
flow.forEach(function(phase, index) => {
if (!index && !returning) {
returning = Promise.resolve(require(phase));
} else {
returning.then(require(phase));
}
});
谢谢!!!
最佳答案
你当前所做的相当于
let returning = Promise.resolve(phase);
returning.then(flow[0]);
returning.then(flow[1]);
returning.then(flow[2]);
returning.then(flow[3]);
要获得实际的链接,您需要在代码中执行 returning = returned.then(...)
。但是,您可以(并且应该)通过使用 reduce
来简化它而不是 forEach
(这也解决了不在循环之外进行初始化的问题):
promise = flow.reduce(function(chain, phase) {
return chain.then(phase);
}, Promise.resolve(phase));
请注意,phase
在这里应该是一个函数,因此如果 flow
确实由字符串组成,您可能必须这样做
return chain.then(() => doSomething(phase));
关于javascript - 从 json 构建 Promise 流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38807531/