JavaScript两个异步函数完成后如何运行函数方法详解

2023年11月27日10:38:58

假设我们有两个元素组成的数组,并且两个元素都是两个异步函数。我们需要做一些工作,比如说当两个异步函数的执行都完成时,在控制台上打印一些内容。

我们如何应对这一挑战?

基本上有两种方法可以在完成一些异步任务时执行某些任务-

  • 兑现承诺

  • 使用异步/等待功能

但是,当代码包含处理许多(不止一个)异步函数时,则前者的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

  • 更新时间:2023年11月27日10:38:58 ,共 767 字。