简体   繁体   中英

Chain execution of array of promises in javascript

I am trying to create a chain of promises where each promise waits for the previous promise before getting executed.

 const syncStatusChanges = () => { return new Promise((resolve, reject) => { console.log("in") setTimeout(() => { console.log("done") resolve({ done: true }) }, 2000); }); } const run = () => { const promises = [syncStatusChanges(), syncStatusChanges()] promises[0].then(res => { console.log("done 1") promises[1].then(res => { console.log("done 2") }) }) } run()

In this example the output is:

in
in
done
done 1
done
done 2

But I want it to be:

in
done
done 1
in
done
done 2

I also want it to work for any n number of functions. I saw this answer but the output is the same!

var promise = statusChangeCalls[0];
for (var i = 1; i < statusChangeCalls.length; i++)
    promise = promise.then(statusChangeCalls[i]);

As it is written in comments. You are executing the functions in the array itself. What i understood by seeing your output. below run function can help you.

  const run = () => {
  const promise = syncStatusChanges();
  promise.then(res => {
     console.log("done 1")
     syncStatusChanges().then(res => {
         console.log("done 2")
     })
  })
}

Promise executes eagerly. It does not wait to register the then function. You can look for observable , they are lazy in execution. Basically they wait until you subscribe them.

For your second doubt about loop. You can use async await keyword to achieve chaining. Just pass number as an parameter in runInLoop function to execute promise that many times.

const runInLoop = async(numberOfPromisesCall)=> {
  for (let i = 0; i < numberOfPromisesCall; i++){
       await syncStatusChanges();
       console.log(`done ${i + 1}`);
  }
} 
runInLoop(5)

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