ES6 Promise.all 进度

2024-05-08

在进一步行动之前,我有几个需要解决的承诺。

Promise.all(promises).then((results) => {
  // going further
}); 

有什么办法可以让我取得进展吗?Promise.all承诺?

从文档看来,这不可能 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all. And 这个问题 https://stackoverflow.com/questions/32260367/progress-of-promises/32260450也不回答。

So:

  • 您不同意这很有用吗?我们不应该查询这个功能吗?
  • 目前如何手动实现呢?

我已经创建了一个可以重复使用的小辅助函数。

基本上像平常一样传递你的承诺,并提供回调来根据进度做你想做的事情。

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)}`);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ES6 Promise.all 进度 的相关文章

随机推荐