javascript - How do I implement recursive promises? -


i have written retry mechanism should return 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 call:

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

i once count >= 4 , resolve called able trigger above "then".

you need resolve inner promise new one, return this.connect() 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 resolve new recursive promise resolve(this.connect());.

check 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}`));


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -