sending multiple api calls in javascript

To make multiple API calls simultaneously in JavaScript, you can use the Promise.all() method with async/await. The Promise.all() method takes an array of promises and resolves them all together.

index.tsx
async function fetchData() {
  const [userData, postsData, commentsData] = await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json()),
    fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()),
    fetch('https://jsonplaceholder.typicode.com/comments').then((response) => response.json())
  ]);

  console.log(userData);
  console.log(postsData);
  console.log(commentsData);
}

fetchData();
479 chars
14 lines

In the example above, we are making three API calls using fetch() and returning their responses as JSON. By wrapping them in Promise.all(), we wait for all three calls to complete before continuing with the await keyword. Once all three promises are resolved, we destructure the resulting data into three separate objects and log them to the console.

Note that using async/await is just one way to handle multiple API calls, you could also use other methods like Promise.all() with .then().

gistlibby LogSnag