简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM