Search code examples
javascriptes6-promise

ES6 Promise.all progress


I have several promises that I need to resolve before going further.

Promise.all(promises).then((results) => {
  // going further
}); 

Is there any way I can have the progress of the Promise.all promise?

From the doc, it appears that it is not possible. And this question doesn't answer it either.

So:

  • Don't you agree that this would be useful? Shouldn't we query for this feature?
  • How can one implement it manually for now?

Solution

  • I've knocked up a little helper function that you can re-use.

    Basically pass your promises as normal, and provide a callback to do what you want with the progress..

    function allProgress(proms, progress_cb) {
      let d = 0;
      progress_cb(0);
      for (const p of proms) {
        p.then(()=> {    
          d ++;
          progress_cb( (d * 100) / proms.length );
        });
      }
      return Promise.all(proms);
    }
    
    function test(ms) {
      return new Promise((resolve) => {
        setTimeout(() => {
           console.log(`Waited ${ms}`);
           resolve();
         }, ms);
      });
    }
    
    
    allProgress([test(1000), test(3000), test(2000), test(3500)],
      (p) => {
         console.log(`% Done = ${p.toFixed(2)}`);
    });