我通过具有不同 url 的 map 向服务器发出请求,然后我将数据设置为 State 并将其用于输出。我希望请求是连续的,但有时它们无法正常工作并出现错误,如何编写正常数据检索的代码?
const urlList = ["countries", "states", "cities", "users"];
componentDidMount() {
urlList.map( (url, index) => {
return servicesAPI.getResourse(url).then( (body) => {
index !== 3 ? this.setState({
dataAPI : [...this.state.dataAPI, body] }) :
this.setState({
dataAPI : [...this.state.dataAPI, body],
loaded: true
})
})
})
export default class ServicesAPI {
_apiBase = `http://localhost:3001/`;
async getResourse(url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` +
`, received ${res.status}`)
}
return await res.json();
}
最佳答案
使用Promise.all();
componentDidMount() {
const fetchPromises = [];
urlList.forEach( (url, index) => {
fetchPromises.push(servicesAPI.getResourse(url));
});
const allResourcesPromise = Promise.all(fetchPromises);
allResourcesPromise.then(data => {
// list with responses
}).catch(err => {
console.log(err.toString());
});
}
示例: https://jsbin.com/vevufumano/1/edit?html,js,console,output
此外,在可能的情况下,您可以使用 async/await 来获得更简洁的代码。
关于javascript - 如何在循环中使用 Fetch 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935614/