javascript - Calling another prototype method after promise completed -
i have following code in node.js file;
gamehelperauth.prototype.getuserviaapi = promise.method(function (authcookie, callback) { // user api }); gamehelperauth.prototype.getobjectfromcache = promise.method(function (authcookie, callback) { // user 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, 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; });
i access instance method instance method once promise completed. looks loses it's context , cannot find function anymore. (please see calling getuserviaapi method)
is there way me reach method without creating new instance of class?
as far can see, simplest fix here declare var self = this
in first line of .getuser()
, use self
instead of this
inside .then
callback.
alternatively if you're using node 4+ es6 compatibility, use "arrow function" outer .then
callback inherits lexical this
instead of contextual this
:
return this.getobjectfromcache() .then((result) => { if (result) { return callback(null, result); } else { // not found in cache, api return this.getuserviaapi(authcookie) .then(function (apiresult) { return callback(null, apiresult); }).catch(function (err) { throw err; }); } }) .catch(function (err) { throw err; });
nb: note addition of return
in first line , in else
clause, necessary ensure function , branch both correctly return promise.
fwiw, think can refactor substantially eliminating repeated call return callback(...)
through chaining .then
:
gamehelperauth.prototype.getuser = function (authcookie, callback) { return this.getobjectfromcache() .then(result => result || this.getuserviaapi(authcookie)) .then(result => callback(null, result)); }
i've removed both .catch
blocks - doing .catch(function(err) { throw err })
no-op - aiui throw
make caller end in own .catch
block might let entire promise reject anyway.
Comments
Post a Comment