javascriptreduxpolymer-3.x

How to resolve a Promise only after a state change


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

  1. how we can call a variable
  2. how to make this work inside my Class I tried it with a 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.


Solution

  • 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();
        }
    
    }