2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
為了Promise.all()工作,你需要從channels.map. 您可以返回每個(gè)元素,然后使用列表Promise.all來(lái)存儲(chǔ)它們。
示例(未測(cè)試):
const [channelAndReadsArray, setChannelAndReadsArray] = useState()
const requests = channels.map((currentChannel) =>
axios.get(serverRestAddress)
.then((result) => ({
channel: currentChannel,
reads: result
}))
)
Promise.all(requests).then((elements) => {
setChannelAndReadsArray(elements)
});
if (!channelAndReadsArray) {
return null
})
channelAndReadsArray.map(console.log)

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
該request數(shù)組將是空的,因?yàn)槟鷽](méi)有從 .map 返回任何內(nèi)容,一種更簡(jiǎn)潔的方法可能是不使用異步代碼推送到數(shù)組中
const [channelAndReadsArray, setChannelAndReadsArray] = useState();
const requests = channels.map(async (currentChannel) => {
return axios.get(serverRestAddress...)
.then((result) => {
var element = {}
element.channel= currentChannel;
element.reads= result;
return result;
})
});
Promise.all(requests).then((results) => { setChannelAndReadsArray(results)});
if (!channelAndReadsArray) {
return null
});
channelAndReadsArray.map((channelAndReads)=>{
console.log(channelAndReads)
});
添加回答
舉報(bào)