I have an method in my JS class and in the callback of a Promise, I want it to call another class method.
class MyClass {
myClassMethod(arg1) {
// this method did get called
}
aSecondClassMethod() {
//...
}
methodWithPromise() {
var myClassMethod = this.myClassMethod;
let aPromise = methodReturnPromise();
aPromise.then(function (value) {
myClassMethod(value);
}
}
So I create a var calls myClassMethod
and set that to this.myClassMethod
. And when I debug the code, myClassMethod did get called in the then
callback of the Promise.
The problem I am having is when my myClassMethod()
calls other class method(), ie
myClassMethod(args) {
aSecondClassMethod();
}
I get error saying aSecondClassMethod
is undefined. I tried
myClassMethod(args) {
this.aSecondClassMethod();
}
But it gives me the same error. I think I can work around this by declaring a var for each of the class method that myClassMethod() calls.
var aSecondClassMethod= this.aSecondClassMethod;
But that seem cumbersome to maintain the code going forward.
I would like to know if there is a better way to do this.
Use an arrow function, as it captures the this
value of the enclosing context.
aPromise.then(value => this.myClassMethod(value));
I would also recommend using the new () => {}
function notation for defining the class method that contains the promise. Without that (or an old school bind) this
will still be undefined
.
My usual style:
class MyClass {
myClassMethod = (value) => {
//something..
};
methodWithPromise = () => {
somePromise
.then((res) => {
this.myClassMethod(res);
})
.catch((err) => {
console.error(err);
return;
});
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.