Skip to content

Instantly share code, notes, and snippets.

@dnafication
Created July 21, 2022 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnafication/fa1f7a41023a5f8dfddff8e4c2f01ede to your computer and use it in GitHub Desktop.
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
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