0

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?

1 Answer 1

1

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
    }
  })
}

Sign up to request clarification or add additional context in comments.

4 Comments

But this way can I use finalArray outside of this Promise.all?
You can use await.
i updated the answer using await. by doing so, you can use finalArray.
Thanks I had to rearrange my code for a little bit to make it work, but this helped a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.