如何在一个异步函数执行完成之后运行一个函数- JavaScript
假设我们有一个由两个元素组成的数组,这两个元素都是两个异步函数。当两个异步函数的执行完成时,我们需要做一些工作,例如在控制台中打印一些内容(出于这个问题的目的)。
我们可以如何应对这一挑战?
在某些异步任务完成后执行某些任务基本上有两种方法 -
- 使用promise
- 使用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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP