Javascript 链中有if-else条件
我有一个承诺链,在一些点中我有if-else条件,如下所示:Javascript 链中有if-else条件,javascript,node.js,asynchronous,promise,bluebird,Javascript,Node.js,Asynchronous,Promise,Bluebird,我有一个承诺链,在一些点中我有if-else条件,如下所示: .then(function() { if(isTrue) { // do something returning a promise } else { // do nothing - just return return; } }) .then(function() { ... }) 老实说,我不喜欢这种式样。我觉得不对。我的意思是只使用简单的返回,没有任何东西。你有什么办法
.then(function() {
if(isTrue) {
// do something returning a promise
} else {
// do nothing - just return
return;
}
})
.then(function() {
...
})
老实说,我不喜欢这种式样。我觉得不对。我的意思是只使用简单的返回,没有任何东西。你有什么办法让这段代码看起来不一样吗?否则{return;}部分可以完全省略,而不改变代码的含义:
.then(function() {
if (isTrue) {
// do something returning a promise
}
})
默认情况下,函数返回未定义的值。我想您已经测试了代码。并认识到这不是你所期望的那样。让我解释一下:
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)
@JonathanBrooks和模式的变化应该在哪里?然后会自动继续到下一个吗?正如我所说,这相当于你目前拥有的。是的,它将使用未定义的值进行解析并调用下一个。然后使用该值进行回调。