javascript / Node.js
how can I retrieve a reference to this/object inside a promise.then ?
var controller = new MyController(params);
controller.action_send();
/////////////////////////////////
class MyController{
constructor(params)
{
this.params = params;
}
action_send()
{
var promise = ext_lib.send();
promise.then(
function(details) {
this.action_save(details);
//(node:27014) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'action_save' of undefined
});
}
action_save(details)
{
save (this.params, details);
}
}
a PHPStorm warning says Warns against a common mistake of trying to reference a member of an ECMAScript class via this. qualifier in a nested function that is not a lambda. this in a nested function that is not a lambda is the function's own 'this' and doesn't relate to the outer class.
tks from now
Use an arrow function.
Unlike a regular function, an arrow function does not bind this
. Instead, this is bound lexically (i.e. this keeps its meaning from its original context).
Here are more details about it Arrow Functions