I am trying to resolve a Promise only after a certain condition is met outside the promise:
class myClass extends ... {
render() {
...
this.fetch();
....
}
fetch(){
Promise.all([
....,
....,
....
]).then( () => {
// new Promise or somthing like that
// wait for state changed to resolve it
}
).then(
// do something
)
}
stateChanged(state){
if(condition){
// resolve promise from here
}
}
}
I tried to implement it in similar way to this question Resolve Javascript Promise outside function scope but I do not understand
this.waitForPromise = null
variable, but when I call
it later this.waitForPromise()
I get a is not a function Type error.class myClass extends ... {
render() {
...
this.fetch();
....
}
constructor(){
this._waitForPromise = null;
}
fetch(){
Promise.all([
....,
....,
....
]).then( () => {
new Promise(function(resolve, reject) {
this._waitForPromise = resolve;
});
}
).then(
// do something
)
}
stateChanged(state){
if(condition){
this._waitForPromise();
}
}
}
Any help and explanation is much appreciated.
You have a closure issue using this
, so capture it first.
You should return the promise in your then
.
You should check to see if promise is created when state changes.
Keep in mind you can only invoke one of resolve/reject, and only once.
class myClass extends ... {
render() {
...
this.fetch();
....
}
constructor(){
this.resolve = null;
this.state = null; // TODO initial state
}
fetch(){
const that = this;
Promise.all([
....,
....,
....
]).then( () => {
return new Promise(function(resolve, reject) {
that.resolve = resolve;
that.checkState();
});
}
).then(
// do something
)
}
checkState(){
if(condition && this.resolve){
this.resolve();
this.resolve = null; // set to null to ensure we don't call it again.
}
}
stateChanged(state){
this.state = state;
this.checkState();
}
}