Home > Software engineering >  Not data on new array poolList when use axios, but console.log still have data
Not data on new array poolList when use axios, but console.log still have data

Time:12-06

I got trouble when creating API using axios. The new array received no contain data but when I run console.log(response), it shows data (see image attach). Anyone can help me for this issue

router.get('/', async (req, res) => {
    const pools = [
        'pool1',
        'pool2',
    ]
    const poolList = pools.map(async pool => {
        const response = await axios.get(`https://example.com/pools/${pool}/summary.json`)
        console.log(response)
        return {
            response
        }
    })
    res.send({
        poolList
    })
})

enter image description here

CodePudding user response:

Its because of async in pools.map(async pool => {. The expected result of poolList is an array of promises.

try to await all

const pools = [
    'pool1',
    'pool2',
]
const poolList = await Promise.all(pools.map(async pool => {
    const response = await axios.get(`https://example.com/pools/${pool}/summary.json`)
    console.log(response)
    return {
        response
    }
}));


res.send({
    "res": poolList
})

CodePudding user response:

Problem

Your poolList is an array of promises. You're then trying to respond with these promises as JSON. This will look something like the following because when promises are stringified, they become empty objects

{
  "poolList": [{}, {}]
}

Solution

What I suspect you actually want is the following...

router.get('/', async (req, res) => {
  const pools = [
    'pool1',
    'pool2',
  ]

  try {
    const poolList = await Promise.all(pools.map(async pool => {
      const { data } = await axios.get(`https://example.com/pools/${encodeURIComponent(pool)}/summary.json`)
      return data // resolve with the data, not the full Response object
    }))

    res.json({ poolList })
  } catch (err) {
    console.error(err)
    res.status(500).send(err)
  }
})

This creates an array of promises that resolve with the remote data (each summary.json) and waits for each of those promises, resulting in an array of data.

This will respond with something like

{
  "poolList": [
    { /* pool1/summary.json */ },
    { /* pool2/summary.json */ }
  ]
}
  • Related