Created
July 21, 2022 08:22
-
-
Save dnafication/ebe29d29362a2571afde3960fab61c67 to your computer and use it in GitHub Desktop.
Example for a task queue in node.js using library called `modern-async`. Error handling considered. API looks better than `fastq`
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 { Queue, sleep } = require("modern-async"); | |
const queue = new Queue(3); // create a queue with concurrency 3 | |
async function main() { | |
const array = Array.from(Array(30).keys()); // an array of 100 numbers from 0 to 99 | |
const promises = []; | |
for (const i of array) { | |
promises.push( | |
queue.exec(async () => { | |
console.log(`Starting task ${i}`); | |
await sleep(Math.random() * 10); // waits a random amount of time between 0ms and 10ms | |
if (i === 5) throw Error("something not right"); | |
console.log(`Ending task ${i}`); | |
return i; | |
}) | |
); | |
} | |
try { | |
const results = await Promise.all(promises); | |
console.log(results); // will display an array with the result of the execution of each separate task | |
} catch (error) { | |
console.warn("Error occurred", error.message); | |
console.warn("----------------------------------"); | |
} | |
// all the scheduled tasks will perform with a maximum concurrency of 3 and log when they start and stop | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment