【发布时间】:2020-11-20 12:51:11
【问题描述】:
我对多个 API 调用的 Promise.all 函数有问题。我正在进行多个 api 调用,然后 console.log 结果。在 map 函数中执行 console.log 时,我能够看到结果,但是当尝试设置状态以在 UI 中呈现和显示时,数据不会流向状态。我不知道问题到底出在哪里以及为什么数据没有流向状态。
这是我的代码。
componentDidMount() {
const promises = data.map(id => {
return new Promise((resolve) => {
fetch(`https://example.com/api/ITems/${id.ID}`)
.then(response => {
return new Promise(() => {
response.json()
.then(response => {
console.log(response); // this console log is showing me data into console, but the console.log below in promise.all section is not showing any data
resolve()
})
.catch((error) => {
console.log(error);
})
})
})
})
})
Promise.all(promises).then(results => {
this.setState({Ids: results.data}); // no data is passing to state
console.log(results); // this console.log does not work. when remove the console.log in loop, i cannot see anything. data is not flowing here
})
.catch((error) => {
console.log(error);
})
}
谢谢大家。
【问题讨论】:
-
console.log(error);s 中的任何一个都在记录什么吗? -
嗨@CertainPerformance。控制台没有错误。
-
Promise.all(promises).then(results => { this.setState({Ids: results.data}); console.log(results); })数据不在这里