How to execute an array of synchronous and asynchronous functions in Node.js?
Last Updated :
07 Oct, 2021
Improve
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:
// this is our list of functions
let 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 list
let executeListOfFunctions = async(listOfFunctions) => {
for(let func of listOfFunctions){
await func();
}
}
// calling main function
executeListOfFunctions(listOfFunctions);
Output:
Approach 2: The Idea is same but, Implementation is easy in this approach.
Example:
// this is our list of functions
let 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 list
let executeListOfFunctions = async(listOfFunctions) => {
return Promise.all(listOfFunctions.map(func => func()));
}
// calling main function
executeListOfFunctions(listOfFunctions);
Output: