ES6 Promise.all进度 [英] ES6 Promise.all progress
本文介绍了ES6 Promise.all进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个诺言,我需要进一步解决。
I have several promises that I need to resolve before going further.
Promise.all(promises).then((results) => {
// going further
});
有什么方法可以使 Promise.all
答应?
Is there any way I can have the progress of the Promise.all
promise?
From the doc, it appears that it is not possible. And this question doesn't answer it either.
所以:
- 您不同意这会有用吗?我们不应该查询该功能吗?
- 现在如何手动实现它?
推荐答案
我打开了一个可以重新使用的辅助功能。
I've knocked up a little helper function that you can re-use.
基本上像往常一样通过了您的承诺,并提供回调以完成所需的操作。
Basically pass your promises as normal, and provide a callback to do what you want with the progress..
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)}`);
});
这篇关于ES6 Promise.all进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文