Calling APIs in sequence using async-await

 There are certain cases when we want to call some APIs in a sequence (order) to get some data. For example, let's say we want to fetch data of 1000 students of an university for some analysis. The API given to us fetches only 100 records at a time but supports pagination. Therefore, we need to call the API 10 times, one after the other to get these records. This can be achieved by

  1. Using plain old callbacks.
  2. Using a combination of promises and callbacks.
  3. Using modern JavaScript feature - async-await (both async and await are keywords).
In this article we will discuss method 3 to solve this problem. We will see the implementation in action using an open API. We will be creating a console app using NodeJS (version 14.7 as of writing) and will be using axios for making http calls.

Setting up the project

  1. Create a directory where you want to keep your JavaScript code files. I have named my directory "api-sequence-async-await".
  2. Open your terminal or command prompt and run command - "npm init -y". This will create a package.json file for our app.
  3. Install axios library using npm. Run command - "npm install axios --save".

The interesting stuff

Now, with our project setup, let's start by creating a js file in the directory. Since our code won't be much to spread out in multiple files, let's name our js file as "index.js" (you can name it anything you want).

Before moving on to the implementation, you should read up about async/await from MDN.

We will be using "An API of Ice and Fire" for fetching data. Let's begin by importing axios in our file and creating a function which fetches information about Game Of Thrones characters.


This function returns a promise. We can see the output by calling then function on it. Execute the file using command - "node index.js".


You will see output like below:


This shows that the API is working fine. To demonstrate that characters are getting fetched one after the other, we will keep pageSize to 2. Also, we will modify our getCharacters function a bit to introduce a 1 second delay in API calls so as to visually see data getting printed after each second. Below is the complete implementation.


Executing the above code will give us output like this:


and in the end:

Explanation

Let's start with changes in getCharacters function. Earlier, this function was returning a promise returned by axios itself, but to have a delay in printing fetched data, we are now returning a promise which resolves after 1 second with a promise returned by axios.

We have created an async function printCharacters which takes number of characters to be printed and calls the API required number of times to print all the characters details. Note how we have used await inside a regular for loop to achieve desired results. Even though async/await are just syntactic sugar over JavaScript promises, using them makes our code cleaner and easier to write.

Assuming that you know about async functions or have read the MDN article mentioned above, printCharacters is a function which returns a promise when called, hence we are calling then function of it to print a statement when the function is done executing. In this case we haven't returned anything from the printCharacters function but had we returned something, it would have come as an argument of then callback which could be used further for some other purpose.

With this you now know how to call API sequentially using async/await. You can find this code on Github as well for your reference. Drop a comment if you have any questions about this or want me to write on some specific topic.

Comments

Popular posts from this blog

What is object destructuring and spread operator in JavaScript?

What are filter, map and reduce functions in JavaScript?

Is competitive programming required to become a good software engineer?