如何链接多个条件承诺? [英] How do I chain multiple conditional promises?
本文介绍了如何链接多个条件承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中,我有条件任务,所有任务都返回承诺.我需要任务按顺序运行.
我当前的实现看起来像这样:
var链= [];if(/*任务A的某些条件*/){chain.push(function(doContinue){taskA().then(doContinue);});}if(/*任务B的某些条件*/){chain.push(function(doContinue){taskB().then(doContinue);});}if(/*任务C的某些条件*/){chain.push(function(doContinue){taskC().then(doContinue);});}var processChain = function(){如果(chain.length){chain.shift()(processChain);} 别的 {console.log(完成所有任务");}};processChain();
这很好用,但是最初我正在寻找一种仅使用Promises创建链并使用 .then
链接所有函数的方法,但是我没有一个可行的解决方案./p>
如果有一种更简洁的方法,仅使用Promises和 then
调用链,那么我想看看一个例子.
解决方案
一种可能的方法:
var promiseChain = Promise.resolve();如果(shouldAddA)promiseChain = promiseChain.then(taskA);如果(shouldAddB)promiseChain = promiseChain.then(taskB);如果(shouldAddC)promiseChain = promiseChain.then(taskC);返回promiseChain;
另一个:
返回Promise.resolve().then(shouldAddA&& taskA).then(shouldAddB&& taskB).then(应该AddC&& taskC);
In my code I have conditional tasks, which all return a promise. I need the tasks to run in sequence.
My current implementation looks something like this:
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();
This works fine, but initially I was looking for a way to create the chain using only Promises and chaining all functions using .then
, but I wasn't able to get a working solution.
If there's a cleaner way using only Promises and chains of then
calls, then I'd love to see an example.
解决方案
One possible approach:
var promiseChain = Promise.resolve();
if (shouldAddA) promiseChain = promiseChain.then(taskA);
if (shouldAddB) promiseChain = promiseChain.then(taskB);
if (shouldAddC) promiseChain = promiseChain.then(taskC);
return promiseChain;
Another one:
return Promise.resolve()
.then(shouldAddA && taskA)
.then(shouldAddB && taskB)
.then(shouldAddC && taskC);
这篇关于如何链接多个条件承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文