Fun with promises today ... I'm trying to figure out why I can't refer to this.promise to resolve it with another method, it's always null.
Any enlightenment is appreciated :)
export default class Example {
constructor() {
this.promise = null
}
test() {
this.promise = new Promise((resolve, reject) => {
this.something()
}).then(resolve => {
// resolved, do something else
}).catch(reject => {
console.log('reject', reject)
})
}
something() {
this.promise.resolve()
}
}
CodePudding user response:
You're trying to use this.promise
in something
before it's value changes from null
. Another way to do this is to pass the resolve
as an argument:
class Example {
constructor() {
this.promise = null;
}
test() {
this.promise = new Promise((resolve, reject) => {
this.something(resolve);
}).then(result => {
console.log('resolve', result);
}).catch(error => {
console.log('reject', error);
});
}
something(resolve) {
resolve(1);
}
}
const example = new Example();
example.test();