如何在 p-limit 中使用 limit.pendingCount 变量?

How to use the limit.pendingCount variable in p-limit?

我正在使用 p-limit 包来限制使用 Promise.all 发出的并发请求数。

我想显示总请求的进度,看到库里有个变量limit.pendingCount

我的问题是如何使用该变量来报告进度,当我控制台记录该变量时,它只有 returns 最终值为 0。

(async () => {
       const result = await Promise.all(promises);

       // eslint-disable-next-line
          console.log(limit.pendingCount);

由于您正在 await-ing Promise.all 调用,所有承诺将在您到达 console.log 语句时完成。

尝试在最初不 await-ing 承诺的情况下检查未决计数。 await-ing 承诺之后的任何代码只会在所有承诺完成后执行(即待定计数为 0)。

const numThreads = 2;
const numPromises = 4;

const pLimit = require("p-limit")
const limit = pLimit(numThreads);
const promises = new Array(numPromises).fill()
    .map((n, i) => i + 1)
    .map(n => limit(() => new Promise(r => {
            console.log(`Started Promise ${n}`);
            setTimeout(r, n * 1000);
        })
        .then(() => console.log(`Completed Promise ${n}`))));
trackProgress('After Promises Initiated', promises);
const result = await Promise.all(promises);
trackProgress('After Promises Awaited', promises);

/**
 * Prints the state of the current pending promises until all pending promises are completed. This works only for this sample; it is not production quality.
 */
function trackProgress(label, promises) {
    console.log(`[${label}] Tracking started.`);
    const printProgress = () => {
        if (limit.pendingCount > 0) {
            console.log(`[${label}] Pending: ${limit.pendingCount} of ${promises.length}`);
            setTimeout(printProgress, 1000);
        }
        else {
            console.log(`[${label}] Tracking completed.`);
        }
    };
    printProgress();    
}

/*
 * Output:
 * "Started Promise 1"
 * "Started Promise 2"
 * "[After Promises Initiated] Tracking started."
 * "[After Promises Initiated] Pending: 2 of 4"
 * "Completed Promise 1"
 * "Started Promise 3"
 * "[After Promises Initiated] Pending: 1 of 4"
 * "Completed Promise 2"
 * "Started Promise 4"
 * "[After Promises Initiated] Tracking completed."
 * "Completed Promise 3"
 * "Completed Promise 4"
 * "[After Promises Awaited] Tracking started."
 * "[After Promises Awaited] Tracking completed."
 */

编辑:

如果你想做一个进度跟踪器,你可能会通过在已执行的承诺的末尾添加回调来获得更好的运气:

const numThreads = 2;
const numPromises = 4;

const pLimit = require("p-limit");
function executeRequests() {
    const limit = pLimit(numThreads);
    let numCompleted = 0;
    console.log(`${100 * numCompleted / numPromises}% Complete`);
    const updateNumCompleted = () => {
        numCompleted++;
        // TODO: Instead of console.log, update UI
        console.log(`${100 * numCompleted / numPromises}% Complete`);
        if (numCompleted >= numPromises) {
            // TODO: Instead of console.log, update UI
            console.log('All promises complete');
        }
    };
    const promises = new Array(numPromises).fill()
        .map((n, i) => i + 1)
        .map(n => limit(() => new Promise(r => {
                console.log(`Started Promise ${n}`);
                setTimeout(r, n * 1000);
            })
            .then(() => {
                console.log(`Completed Promise ${n}`);
                updateNumCompleted();
            })));
    Promise.all(promises);
}
executeRequests();

/*
 * Output:
 * "0% Complete"
 * "Started Promise 1"
 * "Started Promise 2"
 * "Completed Promise 1"
 * "25% Complete"
 * "Started Promise 3"
 * "Completed Promise 2"
 * "50% Complete"
 * "Started Promise 4"
 * "Completed Promise 3"
 * "75% Complete"
 * "Completed Promise 4"
 * "100% Complete"
 * "All promises complete"
 */