简体   繁体   中英

ReactJS axios.post inside a map through array function that returns an object

So I try to map through an array and for each item in the array is a parameter value for a post request. So Im looking for an finalArray with the post request response return value, and need to use the finalArray somewhere else.

const finalArray = paramArray.map(paramKey => {
  axios.post(URL, {
    filters: [
      {
        field: "key", 
        values: [paramKey.key]
      }
    ]
  }).then(res => {
      //res.data.itemName
    });

  return {
    key: paramKey.key,
    text: //res.data.itemName,
    value: paramKey.value
  }
});

so Im not sure how to pass the res.data.itemName outside of the function in .then . I tried declaring a variable before axios such as let name = ""; , and inside .then I have name = res.data.itemName , then I pass the name to text as text: name , but this will give me all empty string. I also tried putting the return inside .then , this way the finalArray gives me undefined values.

Is there any way to pass the res.data.itemName as the value of text ?

You can use Promise.all

 async function() { const promises = paramArray.map(paramKey => axios.post(URL, { filters: [ { field: "key", values: [paramKey.key] } ] }) ); const values = await Promise.all(promises) const finalArray = paramArray.map((paramKey, index) => { return { key: paramKey.key, text: values[index].data.itemName, value: paramKey.value } }) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM