Search code examples
javascriptpromisees6-promise

How do I implement recursive promises?


I have written a retry mechanism that should return a promise:

private connect(): Promise<any> {
      return new Promise((resolve, reject) => {
          if(this.count < 4) {
             console.log("count < 4, count:"+this.count);
             this.count++;
             return this.connect();
            } else {
              resolve("YES");
            }
        });
    }

If I call:

t.connect().then((data:any)=>{ console.log("YES:"+data)});

I would like once count >= 4 and resolve is called to be able to trigger the above "then".


Solution

  • You need to resolve inner promise with the new one, return this.connect() is not enough:

    function connect(): Promise<any> {
      return new Promise((resolve, reject) => {
        if (this.count < 4) {
          console.log("count < 4, count:" + this.count);
          this.count++;
          resolve(this.connect());
        } else {
          resolve("YES");
        }
      });
    }
    

    Note, how you resolve with new recursive promise with resolve(this.connect());.

    Check the demo below.

    function connect() {
      return new Promise((resolve, reject) => {
        if (this.count < 4) {
          console.log("count < 4, count:" + this.count);
          this.count++;
          resolve(this.connect());
        } else {
          resolve("YES");
        }
      });
    }
    
    const t = {count: 0, connect}
    
    t.connect().then(data => console.log(`YES: ${data}`));