Mojimi
Mojimi

Reputation: 3161

Dynamically chained/hierarchical Promises

How can I have a dynamic number of promises resolve in sequence? As in, wait for the one before being done before being called.

In essence I want them to be called in sync, but I can't use await/async in my environment

This is what I've tried so far but it only works with the first and last being called :

class MyClass{
    constructor(t){
    this.time = t
  }
  load(){
    return new Promise(resolve => {
        setTimeout( () => {
        console.log(this.time);
        resolve(this.time);
      }, 1000/this.time)
    })
  }
}

let pChain;
for(i=1; i<5; i++){
    if(!pChain){
    pChain = new MyClass(i).load();
  }else{
    pChain = pChain.then( t => new MyClass(i).load())
  }
}

pChain.then();

Upvotes: 0

Views: 79

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

You're very close. You just have a bug in your loop counter. Change this:

for(i=1; i<5; i++){

to this:

for(let i=1; i<5; i++){

With your existing code, i is implicitly made into a global var. Your code loops through, setting up the promise chain. Then when the promises start resolving, i is now 5, and so all but the first promise end up using 5 instead of the expected number.

If you instead use let, then there will be a new binding of the variable each time through the loop. So each call to MyClass(i) will see its own correct number.

Upvotes: 2

Related Questions