首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Conditional then in promises (bluebird)

Conditional then in promises (bluebird)
EN

Stack Overflow用户
提问于 2015-12-15 00:10:36
回答 3查看 8.2K关注 0票数 4

我想做的是

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .if(ifC, doC)
  .else(doElse)

我认为代码是很明显的?不管怎么说:

当一个特定的条件(也是一个承诺)被给出时,我想调用一个承诺。我可以做一些像这样的事情

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .then(function(){
    ifC().then(function(res){
    if(res) return doC();
    else return doElse();
  });

但这感觉相当冗长。

我正在使用bluebird作为promise库。但我猜,如果有这样的东西,它在任何promise库中都是一样的。

EN

回答 3

Stack Overflow用户

发布于 2017-08-24 22:57:31

基于this other question,这是我想出的一个可选选项:

注意:如果你的条件函数真的需要一个promise,看看@TbWill4321的答案

针对optional then()的答案

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .then((b) => { ifC(b) ? doC(b) : Promise.resolve(b) }) // to be able to skip doC()
  .then(doElse) // doElse will run if all the previous resolves

改进了@jacksmirk对conditional then()的回答

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()

EDIT:我建议您看看Bluebird关于拥有promise.if() HERE

的讨论

票数 5
EN

Stack Overflow用户

发布于 2015-12-15 00:13:43

您不需要嵌套的.then调用,因为ifC似乎无论如何都会返回一个Promise

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .then(ifC)
  .then(function(res) {
    if (res) return doC();
    else return doElse();
  });

你也可以提前做一些跑腿的工作:

代码语言:javascript
运行
复制
function myIf( condition, ifFn, elseFn ) {
  return function() {
    if ( condition.apply(null, arguments) )
      return ifFn();
    else
      return elseFn();
  }
}

getFoo()
  .then(doA)
  .then(doB)
  .then(ifC)
  .then(myIf(function(res) {
      return !!res;
  }, doC, doElse ));
票数 4
EN

Stack Overflow用户

发布于 2016-11-24 23:45:02

我想你正在寻找像this这样的东西

下面是你的代码的例子:

代码语言:javascript
运行
复制
getFoo()
  .then(doA)
  .then(doB)
  .then(condition ? doC() : doElse());

必须在启动链之前定义条件中的元素。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34271606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档