在 promises 链中有 if-else 条件

Having if-else condition inside promises chains

我有一个 promises 链,在某些点内我有 if-else 如下条件:

.then(function() {

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

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

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

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

默认情况下,函数执行 return undefined

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

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)