【问题标题】:JavaScript Promise.all - how to check resolve status?JavaScript Promise.all - 如何检查解析状态?
【发布时间】:2018-11-11 18:32:30
【问题描述】:

假设我有一个 promises 数组,每个元素都是一个 AJAX 调用,用于获取视图的图像 (png)。

const images = Promise.all(views.map(view => {
   return fetch(`/sites/${siteId}/views/${view.id}/image/`);
}));

是否有可能使用 Promise.all 检查承诺解决的当前状态?如果没有,还有其他方法吗?

例如,如果下载了 10 / 20 张图片,我想给用户一个反馈,我们已经为他下载了 50% 的图片。

【问题讨论】:

    标签: javascript arrays asynchronous promise


    【解决方案1】:

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

    【讨论】:

    • @rafal 很高兴为您提供帮助 :)
    • 我不能这样做吗let progress = 0; const images = Promise.all(views.map(view => { return fetch(`/sites/${siteId}/views/${view.id}/image/`).then(() => progress++); }));
    【解决方案2】:

    无需使用setInterval。仅在更新时更新进度。

    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 + "%");
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      相关资源
      最近更新 更多