我有以下内容:
const [channelAndReadsArray, setChannelAndReadsArray] = useState()
var channelAndReads = []
const requests = channels.map((currentChannel) => {
axios.get(serverRestAddress...
.then((result) => {
var element = {}
element.channel = currentChannel;
element.reads = result;
channelAndReads.push(element);
})
})
Promise.all(requests).then(() => {
setChannelAndReadsArray(channelAndReads)
});
...
if (!channelAndReadsArray) {
return null
})
channelAndReadsArray.map((channelAndReads) => {
console.log(channelAndReads)
})
这在控制台日志中给了我空值。
我不确定这是怎么回事
最佳答案
为了使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)