我在我的node.js文件中有以下代碼;承諾完成後調用另一個原型方法
GameHelperAuth.prototype.GetUserViaApi = Promise.method(function (authCookie, callback) {
// get user from API
});
GameHelperAuth.prototype.GetObjectFromCache = Promise.method(function (authCookie, callback) {
// get user from Cache
});
GameHelperAuth.prototype.GetUser = function (authCookie, callback) {
// check cache
this.GetObjectFromCache()
.then(function (result) {
if (result) {
return callback(null, result);
}
else {
// not found in cache, get it from API
// **NOT WORKING HERE - undefined error**
this.GetUserViaApi(authCookie)
.then(function (apiResult) {
return callback(null, apiResult);
}).catch(function (err) {
throw err;
});
}
})
.catch(function (err) {
throw err;
});
一旦承諾完成,我想從另一個實例方法訪問我的實例方法。但它看起來失去了它的上下文,無法再找到功能。 (請看我在哪裏打電話給GetUserViaApi方法)
有沒有什麼辦法讓我達到該方法,而不創建我的課程的新實例?
不要採取回調參數 - 返回承諾。如果您必須使用回調,請使用nodeify進行正確的翻譯 –
您是否使用'var self'或箭頭函數解決方案? – Alnitak
現在就像我用自己一樣容易實現。將重構爲下一版本的箭頭。 –