Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to run a function after two async functions complete - JavaScript
When working with multiple asynchronous operations in JavaScript, you often need to wait for all of them to complete before executing a final function. This is a common scenario in web development where you might be fetching data from multiple APIs or processing several files concurrently.
There are several approaches to handle this challenge, with Promise.all() being the most efficient for running multiple async operations concurrently.
Using Promise.all() (Recommended)
Promise.all() executes multiple promises concurrently and waits for all of them to resolve. It's the optimal choice when you need all operations to complete regardless of their individual timing.
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
Using async/await
You can also use async/await syntax for better readability, especially in complex scenarios:
const asyncFunction1 = () => {
return new Promise((resolve) => {
setTimeout(() => resolve('async function 1 complete'), 2000);
});
};
const asyncFunction2 = () => {
return new Promise((resolve) => {
setTimeout(() => resolve('async function 2 complete'), 1500);
});
};
const runAfterBoth = async () => {
try {
const results = await Promise.all([asyncFunction1(), asyncFunction2()]);
console.log('Both functions completed:', results);
console.log('Final function executed!');
} catch (error) {
console.log('Error occurred:', error);
}
};
runAfterBoth();
Both functions completed: [ 'async function 1 complete', 'async function 2 complete' ] Final function executed!
Handling Errors with Promise.allSettled()
If you want to run the final function even when some promises fail, use Promise.allSettled():
const promises = [
Promise.resolve('Success!'),
Promise.reject('Failed!'),
new Promise(resolve => setTimeout(() => resolve('Delayed success'), 1000))
];
Promise.allSettled(promises).then((results) => {
console.log('All promises settled:');
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index + 1}: ${result.value}`);
} else {
console.log(`Promise ${index + 1} failed: ${result.reason}`);
}
});
console.log('Final function runs regardless of individual failures');
});
All promises settled: Promise 1: Success! Promise 2 failed: Failed! Promise 3: Delayed success Final function runs regardless of individual failures
Comparison of Approaches
| Method | Concurrency | Error Handling | Use Case |
|---|---|---|---|
Promise.all() |
Concurrent | Fails fast on first error | All must succeed |
Promise.allSettled() |
Concurrent | Waits for all, reports individual status | Some can fail |
| Sequential await | Sequential | Stops on first error | Order matters |
Conclusion
Use Promise.all() when you need maximum performance and all operations must succeed. Choose Promise.allSettled() when some operations can fail but you still want to proceed with the final function.
