How to wait for multiple API calls in JavaScript

Ramkumar Khubchandani
2 min readOct 7, 2023

--

  1. Create a function to make an API call. This function should take the API endpoint as an input and return the response from the API.
async function makeAPICall(endpoint) {
const response = await fetch(endpoint);
const data = await response.json();
return data;
}

2. Create a function to make multiple API calls in parallel. This function should take an array of API endpoints as an input and return an array of responses from the APIs.

async function makeMultipleAPICalls(endpoints) {
const promises = endpoints.map(makeAPICall);
const responses = await Promise.all(promises);
return responses;
}

3. Call the makeMultipleAPICalls() function to make multiple API calls in a synchronous way.

const responses = await makeMultipleAPICalls([
'https://api.example.com/v1/endpoint1',
'https://api.example.com/v1/endpoint2',
'https://api.example.com/v1/endpoint3',
]);

4. Do something with the responses from the APIs.

// Do something with the responses from the APIs.

Latest trend in making multiple API calls in a synchronous way in JavaScript:

The latest trend in making multiple API calls in a synchronous way in JavaScript is to use the async/await syntax. This syntax makes it easier to write asynchronous code and to handle errors.

The following example shows how to use the async/await syntax to make multiple API calls in a synchronous way:

// Create a function to make an API call.
async function makeAPICall(endpoint) {
const response = await fetch(endpoint);
const data = await response.json();
return data;
}

// Create a function to make multiple API calls in parallel.
async function makeMultipleAPICalls(endpoints) {
const promises = endpoints.map(makeAPICall);
const responses = await Promise.all(promises);
return responses;
}

// Make multiple API calls in a synchronous way.
const responses = await makeMultipleAPICalls([
'https://api.example.com/v1/endpoint1',
'https://api.example.com/v1/endpoint2',
'https://api.example.com/v1/endpoint3',
]);

// Do something with the responses from the APIs.
console.log(responses);

This code will make the three API calls in parallel and then wait for all of the calls to finish before returning the responses. Once all of the calls have finished, the code will log the responses to the console.

Conclusion:

Making multiple API calls in a synchronous way in JavaScript can be useful for certain tasks, such as loading all of the data needed for a page before rendering the page. However, it is important to use this technique carefully, as it can block the main thread and make the application unresponsive.

Do you want to learn more like this ?

Message me on linkedin

--

--

Ramkumar Khubchandani
Ramkumar Khubchandani

Written by Ramkumar Khubchandani

Frontend Developer|Technical Content Writer|React|Angular|React-Native|Corporate Trainer|JavaScript|Trainer|Teacher| Mobile: 7709330265|ramkumarkhub@gmail.com

Responses (1)