你好的一部分來解決一個承諾,我只能選擇在if語句
我有一個設計這樣的模塊中的功能:
myFunction: function(some args, myBoolean) {
var deffered = q.defer()
if(myBool) {
module.exports.mySecondfunction(args, false, null)
} else {
return module.exports.mySecondfunction(args, true, deffered)
},
mySecondFunction: function(some args, myBoolean, myPromise) {
//Some work here
if(myBoolean) {
//Some work
promise.resolve();
return myPromise.promise
}
}
anotherFunction: function(some args) {
//some work
if (something) {
myFunction(some args, true)
} else {
myFunction(some args, false).then((data) => {
//do stuff
}
}
}
當anotherFunction被觸發並進入「其他人」 的一部分,我的服務器拋出一個錯誤:
TypeError: Cannot read property 'then' of undefined
行,其中失敗是:
myFunction(some args, false).then((data) => {...
你對我的代碼有什麼問題有什麼想法嗎?無論如何只有在布爾值設置爲True時才承諾函數?
你應該幾乎不會傳遞延期。如果它想返回一個,使'mySecondFunction'構造它自己的承諾。 – Bergi
是的,有時候回覆一個承諾,有時候不是一個非常糟糕的主意。只要返回一個已經履行的承諾,如果你在一個沒有任何異步的分支。 – Bergi