2 回答
TA贡献1847条经验 获得超7个赞
为了Promise.all()工作,你需要从channels.map. 您可以返回每个元素,然后使用列表Promise.all来存储它们。
示例(未测试):
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贡献1891条经验 获得超3个赞
该request数组将是空的,因为您没有从 .map 返回任何内容,一种更简洁的方法可能是不使用异步代码推送到数组中
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)
});
添加回答
举报