📜  如何在 NodeJS 中执行一组同步和异步函数?

📅  最后修改于: 2022-05-13 01:56:57.437000             🧑  作者: Mango

如何在 NodeJS 中执行一组同步和异步函数?

我们有一个函数数组,有些函数是同步的,有些是异步的。我们将学习如何按顺序执行所有这些。

输入:

listOfFunctions = [
    () => {
        console.log("Synchronous Function);
    },
    async () => new Promise(resolve => {
        setTimeout(() => {
            resolve(true);
            console.log("Asynchronous Function);
        }, 100);
    }),
    .
    .
    .
]

方法一:把所有的函数都当作异步函数来执行。因为在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);


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


输出:

方法 2:想法相同,但在这种方法中实施起来很容易。

例子:

索引.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);

输出: