使用 axios 創建 API 時遇到問題。新陣列沒有收到包含資料,但是當我運行 console.log(response) 時,它會顯示資料(參見圖片附件)。任何人都可以幫助我解決這個問題
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
})
})
在此處輸入圖片說明
uj5u.com熱心網友回復:
這是因為pools.map(async pool => {. 的預期結果poolList是一系列承諾。
試著等待所有人
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
})
uj5u.com熱心網友回復:
問題
你poolList是一系列的承諾。然后,您嘗試以 JSON 的形式回應這些承諾。這將類似于以下內容,因為當 Promise 被字串化時,它們會變成空物件
{
"poolList": [{}, {}]
}
解決方案
我懷疑你真正想要的是以下內容......
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)
}
})
這將創建一個使用遠程資料(每個summary.json)決議的承諾陣列,并等待每個承諾,從而產生一個資料陣列。
這將回應類似
{
"poolList": [
{ /* pool1/summary.json */ },
{ /* pool2/summary.json */ }
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373740.html
