How to execute an array of synchronous and asynchronous functions in Node.js?
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
// this is our list of functionslet listOfFunctions = [ () => { console.log("Synchronous Function Called"); }, async () => new Promise(resolve => { setTimeout(() => { console.log("Asynchronous Function Called"); resolve(true); }, 100); })] // this function will be responsible// for executing all functions of listlet executeListOfFunctions = async(listOfFunctions) => { for(let func of listOfFunctions){ await func(); }} // calling main functionexecuteListOfFunctions(listOfFunctions); |
Output:
Approach 2: The Idea is same but, Implementation is easy in this approach.
Example:
index.js
// this is our list of functionslet listOfFunctions = [ () => { console.log("Synchronous Function Called"); }, async () => new Promise(resolve => { setTimeout(() => { console.log("Asynchronous Function Called"); resolve(true); }, 100); })] // this function will be responsible// for executing all functions of listlet executeListOfFunctions = async(listOfFunctions) => { return Promise.all(listOfFunctions.map(func => func()));} // calling main functionexecuteListOfFunctions(listOfFunctions); |
Output:



