Search code examples
javascriptnode.jsasynchronousasync-awaitsynchronous

Running multiple functions asynchronously in relation to each other but synchronously in relation to program as a whole


Essentially, I have a try block in an async function that basically looks like the following:

async function functionName() {
  try {
    await function1() // each of function 1, 2, and 3 are async functions
    await function2()
    await function3()
    //some more awaits below this point
  } catch(err) {
    console.log(err)
  }
}

Essentially, I'd like to run function1, function2, and function3 asynchronously in relation to each other (AKA have the three of them run at the same time) but I'd like to wait for all of them to finish before continuing the program (so have the set of 3 run synchronously in relation to the rest of the function). I can't just put the code from function2 and function3 inside of function1 for a variety of reasons, so unfortunately that's not an option. Any help much appreciated!


Solution

  • Assuming all your functions return promises that resolve/reject when the asynchronous operations are done, then you can use Promise.all() to let them all be in-flight at the same time and be notified when they are all done:

    async function functionName() {
      try {
        let results = await Promise.all([function1(), function2(), function3()]);       //some more awaits below this point
      } catch(err) {
        console.log(err)
      }
    }
    

    Or, if you don't want the short-circuit if there's an error, you can use Promise.allSettled() instead and it will notify you only when all requests are done, regardless of whether any of them had an error.

    Keep in mind that only truly non-blocking, asynchronous operations in your functions will actually run in parallel. Any blocking, synchronous code in your functions will still only run one at a time. And, keep in mind that just because a function is tagged as async does not make anything run asynchronously. All the async keyword does is allow you to use await inside the function and make the function automatically return a promise. It does not make anything in the function run asynchronously.

    If you showed your real code rather than pseudo-code, we could comment more specifically about exactly what you're doing and the best way to code it. Please resist the temptation to post questions with only pseudo-code. We can always help better when we see your real code.


    Also, none of this runs synchronously with regard to the program as a whole. It will appear to run synchronously within the body of the function (as the function execution will be suspended by the await). But, as soon as the function hits the await, it immediately returns an unresolved promise and execution after this function call continues. The only way to run someting synchronously with regard to the program as a whole is to use synchronous coding, not non-blocking, asynchronous coding.