我找到了“The Ghost Promise”here这个词,看起来像我的情况。如何解决诺言反模式 - 鬼诺言?
我有这样的代码:
return Q.Promise(function(resolve, reject) {
firstFunctionThatReturnPromise()
.then(function(firstResult) {
_check(firstResult) ? resolve(firstResult) : return secondFunctionThatReturnPromise();
})
.then(function(secondResult) {
console.log(secondResult);
return thirdFunctionThatReturnPromise(secondResult);
})
.then(function(thirdResult) {
resolve(thirdResult);
})
.catch(function(e) {
reject(e)
});
});
的问题是,即使_check
返回true,但它仍然继续到console.log
命令(导致undefined
)。
如果_check
返回false,则事情按预期工作。
所以我的问题是:
- 如果上述行为是正常的吗?
- 如果有更优雅的方式来处理这种情况?
更新1:很多质疑我为什么用Q.Promise
,而不是结果直接返回。这是因为这是一个通用函数,由其他函数共享。
// Usage in other functions
genericFunction()
.then(function(finalResult) {
doSomething(finalResult);
})
.catch(function(err) {
handleError(err);
});
你这里没有鬼,但是一个普通的['Promise' constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi