Home > Blockchain >  Convert .map to an array
Convert .map to an array

Time:12-23

I need to turn that response into a single array I used the concat function of javascript but it didn't work for me

I have an array of id's:

//Arreglo de ID's
const arrayIdImage = data.value.map((item, index) => {
  const id = JSON.parse(item.Image);
  return id
});

image of the array

I use those ids in a get request like this

arrayIdImage.map(async function(item) {
const optionsImage = {
    method: 'GET',
    url: `/items/${item}/thumbnails`,
    headers: {
      'Authorization': `Bearer ${tokenJson}`
    }
  }
  await axios.request(optionsImage).then(function(response) {
    console.log(response.data)
    setUrlGetImage(response.data)
  })
})

the response I get is the following: an array for each id request

response image

CodePudding user response:

You're on the right lines with your approach, but if you want an array of values, then the function you are calling .map() with needs to be returning a value instead of simply calling another method on it. This will be in the form of a promise rather than the value itself, meaning you will have an array of promises, each of which contains one image.

    const thumbnailPromises = arrayIdImage.map(async function(item) {
      const optionsImage = {
        method: 'GET',
        url: `/items/${item}/thumbnails`,
        headers: {
          'Authorization': `Bearer ${tokenJson}`
        }
      }
      return axios.request(optionsImage).then(function(response) {
        return response.data
      })
    })

    const thumbnails = await Promise.all(thumbnailPromises)

You can read up more about Promise.all() and Promise.allSettled() to get more of an idea of how this works, but the important thing is that you send all your requests for data at once (in the .map()) and then wait for them all to be fulfilled, instead of sending one, waiting to hear back, then sending the next, etc.

CodePudding user response:

You can use the Promise.all() to send all of the requests in parallel and wait for them to all complete. ( this is much faster )


const requests = arrayIdImage.map((item) => {
  const optionsImage = {
    method: 'GET',
    url: `/items/${item}/thumbnails`,
    headers: {
      Authorization: `Bearer ${tokenJson}`,
    },
  }
  return axios.request(optionsImage);
});

const results = await Promise.all(requests);
const data = results.map((result) => result.data);

You can iterate the arrayIdImage over id by foreEach function. And inside the forEach function you can fetch the data by id and push the response to an array like this.

const data = []

arrayIdImage.forEach(async (item) => {
  const optionsImage = {
    method: 'GET',
    url: `/items/${item}/thumbnails`,
    headers: {
      Authorization: `Bearer ${tokenJson}`,
    },
  }
  const res = await axios.request(optionsImage)
  data.push(res.data)
})

  • Related