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:
Promise. all does not improve performance. It's the "not waiting for the first promise before starting the second task" that improves performance (if done correctly).
all fail-fast behavior. Promise. all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.
Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.
Checking if All Promises are Resolved Successfullyall() method can be used to check whether all Promises have fulfilled successfully. It accepts an iterable object (e.g. an array) of multiple Promises and returns a Promise. The returned Promise is resolved if all the input Promises passed to it are resolved.
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)}`); });
You can add a .then() to each promise to count whos finished. something like :
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With