简体   繁体   English

JavaScript Promise.all - 如何检查解决状态?

[英]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. 假设我有一系列的promises,每个元素都会对一个视图的图像(png)进行AJAX调用。

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? 有没有可能使用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. 例如,如果下载了10/20个图像,我想给用户一个反馈,我们已经为他下载了50%的图像。

Just increment a variable whenever a promise resolves: 只要promise解决,只需递增一个变量:

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);

No need for using the setInterval . 无需使用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 + "%");
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM