Progress ES6 Promise.all

I have a few promises that I need to solve before moving on.

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

Do I have a way to keep a promise Promise.all?

From the doc, it seems like this is not possible . And this question also does not answer.

So:

  • Don't you agree that would be helpful? Should you request this feature?
  • How can I implement it manually?
+4
source share
2 answers

I performed a small helper function that you can reuse.

In principle, pass your promises as usual, and provide a callback to do what you want with progress.

function allProgress(proms, progress_cb) {
  let d = 0;
  progress_cb(0);
  proms.forEach((p) => {
    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)}`);
});
Run codeHide result
+7

.then() , , . - :

var count = 0;

var p1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 5000, 'boo');
}); 
var p2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 7000, 'yoo');
}); 
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 3000, 'foo');
}); 

var promiseArray = [
  p1.then(function(val) {
    progress(++count); 
    return val 
  }), 
  p2.then(function(val) {
    progress(++count); 
    return val 
  }), 
  p3.then(function(val) {
    progress(++count); 
    return val 
  })
]

function progress(count) {
  console.log(count / promiseArray.length);
}

Promise.all(promiseArray).then(values => { 
  console.log(values);
});
Hide result
+3

Source: https://habr.com/ru/post/1670277/


All Articles