Javascript 如何基于输入有条件地运行函数

Javascript 如何基于输入有条件地运行函数,javascript,node.js,Javascript,Node.js,我希望允许用户指定要运行的函数以及它们的运行顺序 用户的选择最终成为一个数组[‘选项1’、‘选项4’、‘选项2’] 每个选项都与特定函数相关,每个函数都有一个回调 如何首先运行handleOption1,等待回调,然后运行handleOption4,等待回调,然后运行handleOption2(给定上述输入)?使用异步等待,迭代异步函数非常容易。例如: const handlers = [ { key: 'option1', func: async () => { ..

我希望允许用户指定要运行的函数以及它们的运行顺序

用户的选择最终成为一个数组<代码>[‘选项1’、‘选项4’、‘选项2’]

每个选项都与特定函数相关,每个函数都有一个回调


如何首先运行
handleOption1
,等待回调,然后运行
handleOption4
,等待回调,然后运行
handleOption2
(给定上述输入)?

使用异步等待,迭代异步函数非常容易。例如:

const handlers = [
  {
    key: 'option1',
    func: async () => { ... do asyn stuff }
  },
  {
    key: 'option2',
    func: async () => { ... do asyn stuff }
  },
  {
    key: 'option3',
    func: async () => { ... do asyn stuff }
  }
];

const exec = async options => {
  for(const opt of options) {
    const currentHandler = handlers.find(h => h.key == option);
    await currentHandler();
  };
}

// Get user options, execute program

exec(options)
.catch(console.error);

你能把问题中的功能包括进去吗?欢迎来到这里,你尝试过什么?如果你显示你的代码,我相信我们可以帮助我,我没有任何代码显示这一部分,因为我不知道从哪里开始。下面的答案似乎与预期的一样有效(进行了一些调整)。谢谢