我找到了「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