Async call to API within map function (React)

Asked
Active3 hr before
Viewed126 times

8 Answers

functionreact
90%

Stack Overflow Public questions & answers , Stack Overflow help chat ,Instead of using .map() you can use a traditional for or while loop:

Turn your array into an array of promises and then use Promise.all

export const someAction = () => async (dispatch) => {

   try {
      const payload = await Promise.all(myArray.map(id => loaders.myResponseApi(param1, id)));
      dispatch({
         type: types.ARRAY_API,
         payload
      });
   } catch (err) {
      // an error occurred in at least one of the promises
   }

}
load more v
88%

You can now use this executeAllLongRunningTasks function to log your new array of resolved task responses to the console like this:,You can now be confident when it comes to composing asynchronous functions using Array.map! For more information, check out the documentation for async/await syntax.,Or, if you want to use it within an async function or top-level async module:

1...
2
3 executeLongRunningTask = async () => {
   4
   const response = await fetch(this.taskUrl);
   5
   return await response.json();
   6
}
7
8...
load more v
72%

Pretag
 Pretag team - issue, fix, solve, resolve
65%

You want to execute an async function inside a map() call, to perform an operation on every element of the array, and get the results back.,It can be difficult to visualize the example with those placeholder function names, so a simple example of how to use this technique is this Prisma data deletion function I wrote for a Twitter clone to first delete tweets and then users:,Remember, we must wrap any code that calls await in an async function.

const list = [1, 2, 3, 4, 5] //...an array filled with values

const functionThatReturnsAPromise = item => { //a function that returns a promise
   return Promise.resolve('ok')
}

const doSomethingAsync = async item => {
   return functionThatReturnsAPromise(item)
}

const getData = async () => {
   return Promise.all(list.map(item => doSomethingAsync(item)))
}

getData().then(data => {
   console.log(data)
})
load more v
75%

This makes the general pattern of an async map to be Promise.all(arr.map(async (...) => ...)).,And second, it needs to wait for all the Promises then collect the results in an Array. Fortunately, the Promise.all built-in call is exactly what we need for step 2.,The async disposer pattern

const arr = [1, 2, 3];

const syncRes = arr.map((i) => {
   return i + 1;
});

console.log(syncRes);
// 2,3,4
load more v
40%

But the problem is the API function is returning a promise instead of a result at that time.,So, I tried using async-await inside the map function but the map function returns the promise immediately instead of waiting for the API to resolve and return the correct result.,Below is the sample code to resolve all the asynchronous functions that are inside the map.

Below is the sample code to resolve all the asynchronous functions that are inside the map.

const arr = [1, 2, 3, 4, 5];

async function promises() {

   const unresolved = arr.map(async (idx) => {
      await setTimeout(() => {}, 1000);
      return idx;
   })

   const resolved = await Promise.all(unresolved)

   console.log(resolved);
}

promises()
22%

Suppose I have a list of ids, and I want to make an API call on each id.,I recently needed to use async/await inside a map function.,Converting Promises to async/await in JavaScript

const ids = ["id_1", "id_2", "id_3"];
const dataById = ids.map((id) => {
   // make API call
});
load more v
60%

You’re probably used to fetching data in React using axios or fetch. The usual method of handling data fetching is to:,For this tutorial, we will be making use of Create React App. You can create a project by running:,First, we created a function called loadUsers. This will make the API call using the fetch API. And, when it does, it returns a promise which gets resolved. After that, the needed props are made available to the component.

For this tutorial, we will be making use of Create React App. You can create a project by running:

npx create - react - app react - async -demo
load more v

Other "function-react" queries related to "Async call to API within map function (React)"