如何在p-limit中使用pendingCount属性实现调用进度展示?
使用p-limit的pendingCount属性显示API调用进度
问题背景
我需要频繁调用API,使用p-limit库限制并发调用数量,目前希望展示API调用的当前进度。注意到库有pendingCount属性,但不清楚如何使用。此前有类似问题,但已有的答案未使用pendingCount,我希望实现显示“仍有n个API调用待完成”的功能。
原简化代码:
import pLimit from 'p-limit'; const aPromise = []; const urls = [ "https://www.google.com/search?q=1", "https://www.google.com/search?q=2", "https://www.google.com/search?q=3", "https://www.google.com/search?q=4", "https://www.google.com/search?q=5", "https://www.google.com/search?q=6", "https://www.google.com/search?q=7", "https://www.google.com/search?q=8" ]; const limit = pLimit(3); for (const url of urls) { try { aPromise.push(limit(() => fetch(url))); } catch (error) { console.error('An error occurred:', error); } } const res = await Promise.allSettled(aPromise); for (const x of res) { if (x.status == "fulfilled") { //process results } else if (x.status == "rejected") { console.log(`${x.reason}`); } }
解决方案
感谢Simon提供的实现方案,通过定时读取limit.pendingCount属性来计算并实时显示进度:
import pLimit from 'p-limit'; const aPromise = []; const urls = [ "https://www.google.com/search?q=1", "https://www.google.com/search?q=2", "https://www.google.com/search?q=3", "https://www.google.com/search?q=4", "https://www.google.com/search?q=5", "https://www.google.com/search?q=6", "https://www.google.com/search?q=7", "https://www.google.com/search?q=8" ]; const limit = pLimit(3); for (const url of urls) { try { aPromise.push(limit(() => fetch(url))); } catch (error) { console.error('An error occurred:', error); } } // 定时更新进度 let nProgressInterval = setInterval(() => { // 计算已完成百分比,也可直接显示待完成数量:`仍有${limit.pendingCount}个API调用待完成` const completedPercent = Math.round(100 - limit.pendingCount * 100 / aPromise.length); printProgress(completedPercent); }, 1000); const res = await Promise.allSettled(aPromise); // 任务全部完成后清除定时器 clearInterval(nProgressInterval); nProgressInterval = null; for (const x of res) { if (x.status == "fulfilled") { //process results } else if (x.status == "rejected") { console.log(`${x.reason}`); } } // 在控制台同一位置刷新进度,避免重复输出 function printProgress(progress) { process.stdout.clearLine(0); process.stdout.cursorTo(0); process.stdout.write(`进度 ${progress}%`); }
关键说明
limit.pendingCount:p-limit实例的属性,代表当前等待执行的任务数量- 定时任务:通过
setInterval每秒读取一次pendingCount,计算并更新进度 - 控制台优化:
printProgress函数利用process.stdout方法,在同一位置刷新进度文本,保持控制台整洁 - 资源清理:所有API调用完成后必须清除定时器,避免内存泄漏
内容的提问来源于stack exchange,提问作者Andres Lopez
相关产品推荐
相关产品推荐

