【问题标题】:Having if-else condition inside promises chains在承诺链中具有 if-else 条件
【发布时间】:2015-09-12 20:46:26
【问题描述】:

我有一个承诺链,在某些点内我有if-else 条件,如下所示:

.then(function() {

   if(isTrue) {
     // do something returning a promise
   } else {
     // do nothing - just return
     return;
   }
})
.then(function() {
   ...
})

老实说,我不喜欢这种模式。我觉得不对。我的意思是只使用一个简单的回报,没有任何东西。你有什么想法让这段代码看起来不一样吗?

【问题讨论】:

  • @JonathanBrooks 模式的变化应该在哪里?

标签: javascript node.js asynchronous promise bluebird


【解决方案1】:

else { return; } 部分可以简单地完全省略而不改变代码的含义:

.then(function() {
    if (isTrue) {
        // do something returning a promise
    }
})

函数默认返回undefined

【讨论】:

  • 然后会自动继续下一个呢?
  • 正如我所说,它相当于你目前拥有的。是的,它将使用值 undefined 解析并以此调用下一个 .then()s 回调。
【解决方案2】:

我猜你已经测试了代码。并认识到这并不像您预期​​的那样工作。让我解释一下:

function getPromise() {
  callSomeFunctionWhichReturnsPromise().then(function(result) {
    return result; // You hope, that this will be logged on the console? nope, you have to do it here instead.
    console.log('logged in the promise', result); // This will work
  });
}

var result = getPromise();
console.log(result); // undefined!!!

你可以这样做:

function getPromise() {
  return callSomeFunctionWhichReturnsPromise();
}

var result = getPromise();
result.then(console.log); // will call console.log(arguments)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2014-03-21
    • 2021-08-01
    • 2014-12-23
    • 2016-01-07
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多