Let's say, I have an array of promises, each element beign an AJAX call for an image (png) of a view.
const images = Promise.all(views.map(view => {
return fetch(`/sites/${siteId}/views/${view.id}/image/`);
}));
Is there any possibility to check current status of promise resolution using Promise.all? If not, is there any other way?
For example, if 10 / 20 images were downloaded, I would like to give user a feedback, that we have downloaded 50% images for him.
The Promise. all() 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.
all() Method: Fulfillment: The returned promise is fulfilled, If the passed iterable is empty, then this method returns an promise synchronously which is already resolved.
Promise.all fail-fast behaviorPromise.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.all will reject immediately.
It is not safe to resolve/reject promise multiple times. It is basically a bug, that is hard to catch, becasue it can be not always reproducible.
No need for using the setInterval
. Only update the progress when it is updated.
const promises = views.map(view => fetch (`/sites/${siteId}/views/${view.id}/image/`));
const images = Promise.all(promises);
let progress = 0;
promises.forEach(p => p.then(() => {
progress++;
console.log(progress / promises.length * 100 + "%");
}));
Just increment a variable whenever a promise resolves:
const promises = views.map(view => fetch (`/sites/${siteId}/views/${view.id}/image/`));
const images = Promise.all(promises);
let progress = 0;
promises.forEach(p => p.then(() => progress++));
setInterval(() => {
console.log(progress / promises.length * 100 + "%");
}, 1000);
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