I'm testing my code with node v8.9.4
I want to use class methods in my promises chain. But this fails with an error:
(node:68487) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'attr' of undefined
const fsp = require('fs-promise');
class MyClass {
constructor() {
this.attr = 'value';
}
promiseMe() {
console.log(this.attr);
}
main() {
fsp.readdir('.').then(this.promiseMe);
}
}
new MyClass().main();
So I try to use arrow functions as class methods.
But defining an arrow function as a class method is syntactically not correct:
Unexpected token =
promiseMe = () => {
console.log(this.attr);
}
This works, but it is really ugly:
const fsp = require('fs-promise');
class MyClass {
constructor() {
this.attr = 'value';
this.promiseMe = () => {console.log(this.attr);}
}
main() {
this.promiseMe();
}
}
new MyClass().main();
So how can I use class methods in promises?
There is another question regarding this topic: How to use arrow functions (public class fields) as class methods? Unfortunately this doesn't work with my node.js setup.