如何在promise.then()中检索对此的引用? [英] how can I retrieve a reference to this in a promise.then ()?
问题描述
javascript/Node.js
javascript / Node.js
我如何在promise中检索对此对象的引用.然后?
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);
}
}
PHPStorm警告说警告不要尝试通过此方法引用ECMAScript类的成员的常见错误.不是lambda的嵌套函数中的限定符.嵌套函数(不是lambda)中的this是函数本身的"this",与外部类无关.
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
推荐答案
使用箭头功能
.
与常规函数不同,箭头函数不会绑定 this
.取而代之的是,这是按词法绑定的(即,其含义与其原始上下文无关).
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
这篇关于如何在promise.then()中检索对此的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!