Как выполнить массив синхронных и асинхронных функций в NodeJS?

Опубликовано: 26 Июля, 2021

У нас есть массив функций, некоторые функции будут синхронными, а некоторые - асинхронными . Мы узнаем, как выполнять их все по порядку.

Вход:

 listOfFunctions = [
    () => {
        console.log («Синхронная функция);
    },
    async () => новое обещание (resolve => {
        setTimeout (() => {
            разрешить (правда);
            console.log («Асинхронная функция);
        }, 100);
    }),
    .
    .
    .
]

Подход 1. Рассматривайте все функции как асинхронные и выполняйте их. Потому что в Javascript, даже если вы рассматриваете синхронную функцию как асинхронную, проблем нет.

Пример:

index.js




// 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);

Выход:

Подход 2: Идея такая же, но реализация этого подхода проста.

Пример:

index.js




// 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);

Выход: