Skip to content

Instantly share code, notes, and snippets.

@edoves
Created October 28, 2024 07:04
Show Gist options
  • Save edoves/1528c9fd2e4437e85e12b0b4ff2f4022 to your computer and use it in GitHub Desktop.
Save edoves/1528c9fd2e4437e85e12b0b4ff2f4022 to your computer and use it in GitHub Desktop.

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 until firstFunction completes before moving on to secondFunction.
  • await secondFunction(result); runs only after firstFunction has resolved and passed its result.

Using async/await ensures that the code runs in the order you expect and maintains readability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment