如何链接多个条件承诺?

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)

  • 应该指出的是,这两种方法并不完全相同.在方法1中,每个`.then()`都链接不链接.在方法2中,每个`.then()`都是无条件链接的,并且有或没有成功处理程序.每个链接的`.then()`,即使没有处理程序,也会引入下游延迟,因此与方法1相比,方法2将为每个失败的测试引入额外的下游延迟. (4认同)

Tha*_*you 5

您可以使用新的async/await语法

\n\n
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 值abc都在同一范围内可用。这意味着您的条件和返回值可以取决于任务承诺值的任意组合。

\n