In my node.js codebase I have three function I want to prevent to run in parallel. So I want to have a way to run those functions serially at any given time.
On other platforms I am used to setup a serial queue and then dispatch code onto the queue knowing that the execution of dispatched work is going to be serialized.
I am not sure how to do this in Node.js or Javascript. What reliable option do I have in either to serialize the execution of functions?
CodePudding user response:
You can use async
functions for that. Check inline comments for more details:
// Timeout function for example purpose
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
// Your ASYNC functions
const fn1 = async () => {
// Simulate some work by waiting for timeout
await timeout(1000);
console.log(`Function 1 completed`);
}
const fn2 = async () => {
// Simulate some work by waiting for timeout
await timeout(2000);
console.log(`Function 2 completed`);
}
const fn3 = async () => {
// Simulate some work by waiting for timeout
await timeout(500);
console.log(`Function 3 completed`);
}
// Now run them in sequence. You can create
// separate function for this
const runInSeq = async fns => {
// For each function in provided array
// run it, wait till complete, run next
for(const fn of fns) await fn();
}
// Now you can pass all your async functions
// to your runner as an array and it will
// run them in seq
runInSeq([fn1, fn2, fn3]);
And this is one of options how you can create queue
// Timeout function for example purpose
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
// Your ASYNC functions
const fn1 = async () => {
// Simulate some work by waiting for timeout
await timeout(1000);
console.log(`Function 1 completed`);
}
const fn2 = async () => {
// Simulate some work by waiting for timeout
await timeout(2000);
console.log(`Function 2 completed`);
}
const fn3 = async () => {
// Simulate some work by waiting for timeout
await timeout(500);
console.log(`Function 3 completed`);
}
// To run functions in queue you can create some array
// in which you will push additional functions and
// iterate it with some control logic
//
// Create queue array
const fnQueue = [];
// Also create some while loop indicator
let runningWhile = false;
// Queue function
const runInQueue = async fn => {
// Push new function to queue array
fnQueue.push(fn);
// If while loop not running, run it
if(!runningWhile) {
// Set while loop indicator to true
runningWhile = true;
// Run while loop
while(fnQueue.length > 0) {
// Shift array and run function
const fn = fnQueue.shift();
await fn();
}
// After while loop, set indicator to false
runningWhile = false;
}
}
// Add functions to queue with some delays
(async () => {
runInQueue(fn1);
await timeout(1100);
runInQueue(fn2);
await timeout(500);
runInQueue(fn3);
})();