Created
July 21, 2022 08:40
-
-
Save dnafication/fa1f7a41023a5f8dfddff8e4c2f01ede to your computer and use it in GitHub Desktop.
p-limit allows you to call Promise.all but with a concurrency limit. The code example below executes the async function with a concurrency limit of 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { promisify } = require("util"); | |
const sleep = promisify(setTimeout); | |
const doSomething = async (arg) => { | |
console.log(`doing something with ${arg}`); | |
await sleep(1000); | |
if (arg === 5) throw Error("bummer!"); | |
console.log(`done something with ${arg}`); | |
return arg * 10; | |
}; | |
async function run() { | |
// work around to use ESM package in commonjs | |
const pLimit = await import("p-limit"); | |
const limit = pLimit.default(3); | |
const args = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
const result = await Promise.allSettled( | |
args.map((arg) => limit(doSomething, arg)) | |
); | |
console.log(result); | |
} | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment