Home > database >  How can I iterate through an array of objects, make an API call for each object, then set the respon
How can I iterate through an array of objects, make an API call for each object, then set the respon

Time:09-30

I have an array of objects (mergedArray) that I need to iterate through, call an api for each object, then set that response as a new value. Every time I do this the array gets returned with industry: Promise { <pending> }

let responseArray = await Promise.all( mergedArray.map(i =>{
  return (
    {...i, industry: atomTest()}
  )
}))
console.log(responseArray)

Using this function to fetch the data..

const atomTest = async () => {

  await fetch('https://*********', 
  {
    method: 'POST',
    headers: {accept: 'application/json', 'content-type': 'application/json'},
    body: JSON.stringify({
      asset: {identifier: 'ticker', value: 'NKE', assetType: 'equity', market: 'USA'}
    })
  })
  .then(response => response.json())
  .then((response )=> {
    console.log(response.lists[0].name)
    return(response.lists[0].name)
  .catch(err => console.error(err));
}

Replacing 'atomTest()' with a function that just returns a string gives the correct result, how would I do this with an async function? I can't seem to figure out how to let the function wait for the fetch result before moving on.

Any help would be massively appreciated :)

CodePudding user response:

You need to await for the API call to complete in the map callback:

async function callAPI(n) {
    return fetch('https://jsonplaceholder.typicode.com/todos/'   n)
        .then(response => response.json())
}

mergedArray = [1, 2, 3]

async function main() {
    let responseArray = await Promise.all(mergedArray.map(async i => {
        return {i, industry: await callAPI(i)}
    }))

    console.log(responseArray)
}

main()

  • Related