How to execute an array of synchronous and asynchronous functions in Node.js?
Last Updated :
07 Oct, 2021
We have an array of functions, some functions will be synchronous and some will be asynchronous. We will learn how to execute all of them in sequence.
Input:
listOfFunctions = [
() => {
console.log("Synchronous Function);
},
async () => new Promise(resolve => {
setTimeout(() => {
resolve(true);
console.log("Asynchronous Function);
}, 100);
}),
.
.
.
]
Approach 1: Treat all functions as asynchronous functions and execute them. Because in Javascript, even if you treat a synchronous function as asynchronous function, there is no problem.
Example:
index.js
let listOfFunctions = [
() => {
console.log( "Synchronous Function Called" );
},
async () => new Promise(resolve => {
setTimeout(() => {
console.log( "Asynchronous Function Called" );
resolve( true );
}, 100);
})
]
let executeListOfFunctions = async(listOfFunctions) => {
for (let func of listOfFunctions){
await func();
}
}
executeListOfFunctions(listOfFunctions);
|
Output:
Approach 2: The Idea is same but, Implementation is easy in this approach.
Example:
index.js
let listOfFunctions = [
() => {
console.log( "Synchronous Function Called" );
},
async () => new Promise(resolve => {
setTimeout(() => {
console.log( "Asynchronous Function Called" );
resolve( true );
}, 100);
})
]
let executeListOfFunctions = async(listOfFunctions) => {
return Promise.all(listOfFunctions.map(func => func()));
}
executeListOfFunctions(listOfFunctions);
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...