我有以下内容:
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)
})
这使控制台日志中的值为空。 我不确定这是怎么回事
答案 0 :(得分:2)
要使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)
答案 1 :(得分:0)
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)
});