Call async/await Functions in Parallel
To call async/await functions in parallel in JavaScript, you can use Promise.all
to concurrently execute multiple asynchronous functions and wait for all of them to complete. Here's an example:
// Assume you have two asynchronous functions that return promises
async function asyncFunction1() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Async function 1');
resolve('Result from async function 1');
}, 1000);
});
}
async function asyncFunction2() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Async function 2');
resolve('Result from async function 2');
}, 1500);
});
}
// Call both functions in parallel using Promise.all
async function executeParallelFunctions() {
try {
const [result1, result2] = await Promise.all([asyncFunction1(), asyncFunction2()]);
console.log('Results:', result1, result2);
} catch (error) {
console.error('Error:', error);
}
}
// Invoke the function
executeParallelFunctions();
In this example:
asyncFunction1
andasyncFunction2
are two asynchronous functions that return promises.- The
executeParallelFunctions
function usesPromise.all
to call both functions concurrently. - The
await Promise.all([...])
statement waits for all promises to resolve and returns an array of results. - The results are then logged to the console.
This approach is effective for running multiple asynchronous functions in parallel and is especially useful when the functions are independent of each other and don't rely on the results of the others.
Keep in mind that if one of the promises is rejected, Promise.all
will reject with the reason of the first promise that was rejected. Ensure proper error handling as demonstrated in the example.
-
How can I do Base64 encoding in Node.js?
In Node.js, you can use the built-in Buffer class to perform Base64 encoding and decoding. The Buffer class provides methods for encoding and decoding data in various formats, including Base64. Her...
Questions -
Is there a map function for objects in Node.js?
In JavaScript, the map function is typically used with arrays to transform each element of the array based on a provided callback function. If you want to achieve a similar result with objects, you...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github