在承诺链中有if-else条件
我有一个承诺链,并在一些点我有if-else
条件如下:
.then(function() { if(isTrue) { // do something returning a promise } else { // do nothing - just return return; } }) .then(function() { ... })
老实说,我不喜欢这种模式。 我感觉错了。 我的意思是使用一个简单的回报没有任何东西 你有什么想法让这个代码看起来不一样吗?
那else { return; }
else { return; }
部分可以完全省略而不改变代码的含义:
.then(function() { if (isTrue) { // do something returning a promise } })
函数默认返回undefined
。
我想你已经testing了代码。 并认识到,这不像你所期望的。 让我解释一下:
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)