Concurrent Request with Async Await in Javascript

In this article I'll be touching about async, await and Promise.all in Javascript and easiest way to make it faster

Async/Await

Async/Await was introduced by Javascript in ECMAScript 2017 to work with promises functon that returns a promise either resolve() on successful execution or can be rejected using reject(). Await holds the futher execution of function until the promise is returned from the function. Await keyword can only be used if the function uses Async key work before function name.

example:

    async function functionName() {
        try {
            let response = await fetch('/get data');
            let user = await response.json();
        } catch (error) {
            // catches errors both in fetch and response.json
`           alert(error)
        }
    }
    

As above code we are making asychronous API request to fetch data and wait for the response to be returned by using await keyword.

It is totally fine when we have to make a single async call but what if we have to make multiple asynchronous function call to finish our task ?.

we can do two things

1. Async/Await in Serial

        async function doWork() {
            
           let posts =  await axios.get('https://examples/posts')
            console.log({posts})

           let tags = await axios.get('https://example.com/tags')
           console.log({tags})
        }

This is valid function call but you'll notice something here.

  • Make get request to posts
  • Wait for the posts request to complete
  • Console.log posts response
  • Make get request to tags
  • Wait for tags response
  • Console.log tags

The problem here is that we are waiting serially for each network request to complete before starting the next request.

so to address this problem Javascript has a method Promise.all(iterable)

2. Async/Await in Parallel

we need make a single function call and tell Javascript to make request in parallel. In order to stop execution we need to wait forn the promises to return. So we'll use Promise.all method

    await Promise.all(["function call 1 ",'function call 2'])

when we use await on Promise.all, Javascript will wait for the entire array of promises passes to Promise.all to resolve. If one function call rejects whole Promise will be rejected.

   let [posts, tags] = await Promise.all([
        axios.get('https://examples/posts'),
        axios.get('https://examples/tags')
      ])

      console.log({posts})
      console.log({tags})

This code will make request for posts and tags and await for all those promises to complete and passes data each corresponding variables.

You can learn more HERE