Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Promise.all - how to check resolve status?

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.

like image 961
Rafał Bagrowski Avatar asked Jun 01 '18 15:06

Rafał Bagrowski


People also ask

How do you check if all promises are resolved?

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.

Does promise all resolve?

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.

What happens to promise all if one fails?

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.

What happens if you resolve a promise multiple times?

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.


2 Answers

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 + "%");
}));
like image 192
Orhun Alp Oral Avatar answered Oct 19 '22 18:10

Orhun Alp Oral


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);
like image 31
Jonas Wilms Avatar answered Oct 19 '22 19:10

Jonas Wilms