Created
July 21, 2022 08:52
-
-
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.
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() { | |
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