在承诺链中处理早期回报的最佳方式

Best way to handle early returns in chains of promises?

本文关键字:回报 最佳 方式 承诺 处理      更新时间:2023-09-26

在Bluebird中处理早期返回而不抛出错误的最佳方法是什么。例如,我在下面有一个条件:

things.find(1)
  .then(function(thing) {
    if (thing.condition === true) {
      return thing
    } else {
      // early return?
    }
  })
  .then(function(thing) {
    return doStuff(thing)
  })

一旦.then链形成,其自然行为是随着每个阶段的稳定而逐渐运行到完成。

对于"提前退货"(这不是一个好短语,但我们知道你的意思),你有三个选择:

  • 抛出一个错误,或返回一个被拒绝的promise,以绕过所有成功处理程序,直到下一个catch(或链的末端)
  • 返回一个保证永远不会和解的承诺-例如return new Promise()
  • 相应地组成.then链(Esailija的回答)
things.find(1).then(function(thing) {
  if (!thing.condition) return;
  return doStuff(thing)
    .then(...);
    .then(...);
})