Skip to content

Instantly share code, notes, and snippets.

@dnafication
Created July 21, 2022 08:52
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/67dda6830339194e83262b7ccb20598f to your computer and use it in GitHub Desktop.
Save dnafication/67dda6830339194e83262b7ccb20598f to your computer and use it in GitHub Desktop.
p-queue is a full fledged promise queue. It has a lot of advanced use cases. I provide a basic example here.
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() {
const pQueue = await import("p-queue");
const queue = new pQueue.default({ concurrency: 3 });
const args = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = await Promise.allSettled(
args.map((arg) => queue.add(() => doSomething(arg)))
);
console.log(result);
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment