javascript - 有条件的然后在 promise 中( bluebird )

标签 javascript node.js promise

我想做什么

getFoo()
  .then(doA)
  .then(doB)
  .if(ifC, doC)
  .else(doElse)

我觉得代码很明显?无论如何:

我想在给出特定条件(也是 promise )时调用 promise 。我可能会做类似的事情

getFoo()
  .then(doA)
  .then(doB)
  .then(function(){
    ifC().then(function(res){
    if(res) return doC();
    else return doElse();
  });

但这感觉很冗长。

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

最佳答案

基于 this other question ,这就是我想出的可选方案:

Note: if your condition function really needs to be a promise, look at @TbWill4321's answer

optional then() 的答案

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 对条件 then()

的回答
getFoo()
  .then(doA)
  .then(doB)
  .then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse()

EDIT: I suggest you have a look at Bluebird's discussion on having a promise.if() HERE

关于javascript - 有条件的然后在 promise 中( bluebird ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271606/

相关文章:

javascript - 来自较早 promise 的控制台日志出现在来自最新 promise 的控制台日志之后

javascript - 根据谷歌表格中的单元格值变化将电子邮件发送到特定地址

javascript - 简写 JS 到 jQuery

javascript - 如何处理 Node.js URL 对象中的错误

javascript - 我的作业项目 : Stock Price Checker 的异步/等待问题

javascript - 吞下消息 : Error: Uncaught (in promise): [object Undefined]

asynchronous - 为什么这个懒惰的迭代解决不止一次?

javascript - 虚拟化;获取 v-select 字段的根元素

javascript - 具有匹配变量名称的命名函数表达式

javascript - 在 JavaScript 中读取包含 32 位 float 的二进制文件