bum*_*ack 12 javascript promise
在我的代码中,我有条件任务,都返回一个承诺.我需要按顺序运行任务.
我目前的实现看起来像这样:
var chain = [];
if (/* some condition for task A */) {
chain.push(function(doContinue){
taskA().then(doContinue);
});
}
if (/* some condition for task B */) {
chain.push(function(doContinue){
taskB().then(doContinue);
});
}
if (/* some condition for task C */) {
chain.push(function(doContinue){
taskC().then(doContinue);
});
}
var processChain = function () {
if (chain.length) {
chain.shift()(processChain);
} else {
console.log("all tasks done");
}
};
processChain();
Run Code Online (Sandbox Code Playgroud)
这工作正常,但最初我一直在寻找一种方法,只使用Promises创建链,并链接所有函数使用.then
,但我无法得到一个有效的解决方案.
如果有一种更简洁的方式只使用Promise和then
电话链,那么我很乐意看到一个例子.
rai*_*7ow 17
一种可能的方法:
var promiseChain = Promise.resolve();
if (shouldAddA) promiseChain = promiseChain.then(taskA);
if (shouldAddB) promiseChain = promiseChain.then(taskB);
if (shouldAddC) promiseChain = promiseChain.then(taskC);
return promiseChain;
Run Code Online (Sandbox Code Playgroud)
另一个:
return Promise.resolve()
.then(shouldAddA && taskA)
.then(shouldAddB && taskB)
.then(shouldAddC && taskC);
Run Code Online (Sandbox Code Playgroud)
您可以使用新的async
/await
语法
async function foo () {\n let a = await taskA()\n if (a > 5) return a // some condition, value\n\n let b = await taskB()\n if (b === 0) return [a,b] // some condition, value\n\n let c = await taskC()\n if (c < 0) return "c is negative" // some condition, value\n\n return "otherwise this"\n}\n\nfoo().then(result => console.log(result))\n
Run Code Online (Sandbox Code Playgroud)\n\n这样做的好处是 \xe2\x80\x93 除了代码非常平坦且可读(imo) \xe2\x80\x93 值a
、b
和c
都在同一范围内可用。这意味着您的条件和返回值可以取决于任务承诺值的任意组合。