If two asynchronous functions depend on each other, what should be used to maintain execution order?
If two asynchronous functions depend on each other and you need to maintain execution order, you should use async
and await
to control the sequence of execution. The await
keyword ensures that the second function only runs after the first function has completed, preserving the correct order.
Here's an example:
async function firstFunction() {
// Some asynchronous operation
return new Promise(resolve => setTimeout(() => {
console.log("First function complete");
resolve("Result from first function");
}, 1000));
}
async function secondFunction(resultFromFirst) {
// This function depends on the result from the first function
console.log("Second function received:", resultFromFirst);
}
async function main() {
const result = await firstFunction(); // Wait for the first function to complete
await secondFunction(result); // Execute the second function after
}
main();
In this setup:
await firstFunction();
ensures that the execution pauses untilfirstFunction
completes before moving on tosecondFunction
.await secondFunction(result);
runs only afterfirstFunction
has resolved and passed its result.
Using async
/await
ensures that the code runs in the order you expect and maintains readability.