Node.js 异步并发控制:`p-map` 和 `p-limit` 的使用与对比-5. 结合使用

时间:2025-02-18 07:34:51

在某些情况下,你可以结合使用 p-mapp-limit。例如,你可以使用 p-limit 来创建一个并发限制器,然后将其与 p-map 结合使用。

const pMap = require('p-map');
const pLimit = require('p-limit');

async function main() {
    const limit = pLimit(2); // 并发数为 2
    const numbers = [1, 2, 3, 4, 5];

    const results = await pMap(numbers, (num) => 
        limit(() => asyncOperation(num))
    );

    console.log(results);
}

async function asyncOperation(num) {
    // 模拟异步操作
    return new Promise(resolve => setTimeout(() => resolve(num * 2), 1000));
}

main();