gpt4 book ai didi

javascript - Promise 完成后调用另一个原型(prototype)方法

转载 作者:行者123 更新时间:2023-11-28 18:48:57 26 4
gpt4 key购买 nike

我的 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方法)

有什么方法可以让我在不创建类的新实例的情况下达到该方法吗?

最佳答案

据我所知,这里最简单的解决方法是在 .GetUser() 的第一行声明 var self = this ,然后使用 self 而不是 .then 回调中的 this

或者,如果您使用兼容 ES6 的 Node 4+,请使用“箭头函数”作为外部 .then 回调,该回调继承词法 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;
});

注意:请注意在第一行和 else 子句中添加了 return,这是确保函数和分支都正确返回 Promise 所必需的。

FWIW,我还认为您可以通过消除通过链接 .then 重复调用 return callback(...) 来大幅重构这一点:

GameHelperAuth.prototype.GetUser = function (authCookie, callback) {
return this.GetObjectFromCache()
.then(result => result || this.GetUserViaApi(authCookie))
.then(result => callback(null, result));
}

我已经删除了两个 .catch block - 执行 .catch(function(err) { throw err }) 是无操作 - AIUI throw 将使调用者最终进入自己的 .catch block ,因此您不妨让整个 Promise 拒绝。

关于javascript - Promise 完成后调用另一个原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com