在承诺完成后调用另一个原型方法

时间:2016-01-15 23:52:11

标签: javascript node.js oop promise

我在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;
        });

一旦promise完成,我想从另一个实例方法访问我的实例方法。但看起来它失去了它的背景,再也找不到功能了。 (请看我在哪里调用GetUserViaApi方法)

有没有办法让我在不创建班级的新实例的情况下达到该方法?

1 个答案:

答案 0 :(得分:3)

据我所知,此处最简单的解决方法是在var self = this的第一行声明.GetUser(),然后在self内使用this代替.then .then回调。

或者,如果您使用的是具有ES6兼容性的Node 4+,请使用“箭头功能”作为继承词汇this而非上下文this的外部return this.GetObjectFromCache() .then((result) => { if (result) { return callback(null, result); } else { // not found in cache, get it from API return this.GetUserViaApi(authCookie) .then(function (apiResult) { return callback(null, apiResult); }).catch(function (err) { throw err; }); } }) .catch(function (err) { throw err; }); 回调:< / p>

return

注意:请注意在第一行和else子句中添加return callback(...),以确保函数和该分支都正确地返回一个承诺。

FWIW,我也认为你可以通过链接.then取消对GameHelperAuth.prototype.GetUser = function (authCookie, callback) { return this.GetObjectFromCache() .then(result => result || this.GetUserViaApi(authCookie)) .then(result => callback(null, result)); } 的重复调用来大幅度重构:

.catch

我删除了两个.catch(function(err) { throw err })块 - 执行throw是无操作 - AIUI .catch会使调用者最终进入自己的WRITE_EXTERNAL_STORAGE块你也可以让整个承诺无论如何都要拒绝。

相关问题