如何在两个异步函数完成后运行一个函数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 19:24:17

假设我们有一个包含两个元素的数组,其中两个元素都是两个异步函数。当两个异步函数执行完成时,我们需要做一些工作,比如将一些内容打印到控制台(出于这个问题的目的)。

我们如何应对这一挑战?

在完成某些异步任务后,基本上有两种方法可以执行某些任务 −

  • 使用 promises
  • 使用 async/await 函数

但是,当代码包括处理许多(多个)异步函数时,前者的 Promise.all 函数比后者更有优势。

示例

以下是代码 −

const arr = [
   new Promise((resolve, reject) => {
      setTimeout(() => {
         resolve('func1 fired!');
      }, 2000);
   }),
   new Promise((resolve, reject) => {
      setTimeout(() => {
         resolve('func2 fired');
      }, 3000);
   })
];
const lastFunction = () => {
   console.log('this function should be fired at the very last');
};
Promise.all([arr[0], arr[1]]).then((resp) => {
   console.log(resp);
   lastFunction();
}).catch((err) => {
   console.log('something unexpected happened');
})

输出

这将在控制台中产生以下输出 −

[ 'func1 fired!', 'func2 fired' ]
this function should be fired at the very last

相关文章


有用资源