Simple example of my problem
Consider the following situation, where I have a few functions (a
and b
) that I used in a promise-chain in c
:
class SomeClass {
constructor(){
this.v1 = 1;
this.v2 = 2;
}
a() {
return new Promise((resolve, reject) => {
console.log('a', this.v1); // Do something with `this`
resolve();
});
}
b() {
return new Promise((resolve, reject) => {
console.log('b', this.v2); // Do something with `this`
resolve();
});
}
c() {
return this.a().then(this.b); // passing b as argument
}
}
When I call c
and run the chain of promises, this
is undefined in b
.
const sc = new SomeClass();
sc.c().then(() =>{
console.log('done')
}).catch((error) => {
console.log('error', error);
});
Output:
a 1
error [TypeError: Cannot read property 'v2' of undefined]
I know that arrow functions inherit the outer this
, but I am not sure why it is undefined since I am invoking it from c
.