- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to run a function after two async functions complete - JavaScript
Suppose we have an array of two elements with both of its elements being two asynchronous functions. We are required to do some work, say print something to the console (for the purpose of this question) when the execution of both the async function completes.
How can we approach this challenge?
There are basically two ways to perform some task upon completion of some asynchronous task −
- Using promises
- Using async/await functions
But when the code includes dealing with many (more than one) asynchronous functions then the Promise.all function of the former has an edge over the latter.
Example
Following is the code −
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'); })
Output
This will produce the following output in console −
[ 'func1 fired!', 'func2 fired' ] this function should be fired at the very last
Advertisements