Fetch API 请求多个get请求
Fetch API requesting multiple get requests
我想知道如何一次获取多个 GET URL,然后将获取的 JSON 数据放入我的 React DOM 元素中。
这是我的代码:
fetch("http://localhost:3000/items/get")
.then(function(response){
response.json().then(
function(data){
ReactDOM.render(
<Test items={data}/>,
document.getElementById('overview')
);}
);
})
.catch(function(err){console.log(err);});
但是,我想从我的服务器获取额外的 JSON 数据,然后使用传递给它的所有这些 JSON 数据呈现我的 ReactDOM。例如:
ReactDOM.render(
<Test items={data} contactlist={data2} itemgroup={data3}/>,
document.getElementById('overview')
);
这可能吗?如果不是,还有什么其他解决方案可以将多个 JSON 数据提取到我的渲染 ReactDOM 元素中?
使用 Promise.all
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) 的某些实现一次发出多个请求,然后对您的数据执行您想要的操作:
Promise.all([
fetch("http://localhost:3000/items/get1"),
fetch("http://localhost:3000/items/get2"),
fetch("http://localhost:3000/items/get3")
]).then(allResponses => {
const response1 = allResponses[0]
const response2 = allResponses[1]
const response3 = allResponses[2]
...
})
您可以依靠 Promises 在您决定之前执行所有这些操作。如果你习惯了jQuery,你也可以使用jQuery Promises。
在 Promise.all 中,您将强制完成每个请求,然后再继续执行代码
Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]).then(([items, contactlist, itemgroup]) => {
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}).catch((err) => {
console.log(err);
});
但即便如此,fetch 并没有在今天的所有浏览器中实现,所以我强烈建议您创建一个额外的层来处理请求,在那里您可以调用 fetch 或使用回退,假设 XmlHttpRequest
或 jQuery
ajax.
除此之外,我强烈建议您查看 Redux
来处理 React 容器上的数据流。设置会更复杂,但将来会有回报。
2018 年 8 月更新 async/await
截至今天,fetch 已在所有最新版本的主要浏览器中实现,除了 IE11,包装器仍然有用,除非你为它使用 polyfill。
然后,利用更新和现在更稳定的 javascript 功能,如解构和 async/await,您也许可以对同一问题使用类似的解决方案(请参阅下面的代码)。
我相信,尽管乍一看似乎代码多了一点,但实际上是一种更简洁的方法。希望对你有帮助。
try {
let [items, contactlist, itemgroup] = await Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]);
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}
catch(err) {
console.log(err);
};
我需要 json 格式响应,所以我自己添加了一些代码
Promise.all([
fetch(url1).then(value => value.json()),
fetch(url2).then(value => value.json())
])
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
以下是我如何获取多个端点的示例,这可能会对某人有所帮助
const findAnyName = async() => {
const urls = ['https://randomuser.me/api/', 'https://randomuser.me/api/'];
try{
let res = await Promise.all(urls.map(e => fetch(e)))
let resJson = await Promise.all(res.map(e => e.json()))
resJson = resJson.map(e => e.results[0].name.first)
console.log(resJson)
}catch(err) {
console.log(err)
}
}
findAnyName()
Here is a complete example you can check on JSFiddle
或者试试这个:将所有 URL 声明为数组。我们将遍历这个
数组并引用单个 URL 作为数组索引。
constructor(props) {
super(props);
this.state = { World: [], Afghanistan: [], USA: [], Australia: [] };
}
const urls = [
'https://corona.lmao.ninja/v2/all',
'https://corona.lmao.ninja/v2/countries/afghanistan',
'https://corona.lmao.ninja/v2/countries/usa',
'https://corona.lmao.ninja/v2/countries/australia'
];
Promise.all(urls.map(url =>
fetch(url)
.then(checkStatus) // check the response of our APIs
.then(parseJSON) // parse it to Json
.catch(error => console.log('There was a problem!', error))
))
.then(data => {
// assign to requested URL as define in array with array index.
const data_world = data[0];
const data_af = data[1];
const data_usa = data[2];
const data_aus = data[3];
this.setState({
World: data_world,
Afghanistan: data_af,
USA: data_usa,
Australia: data_aus
})
})
function checkStatus(response) {
if (response.ok) {
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
}
function parseJSON(response) {
return response.json();
}
结果
const { World, Afghanistan, USA, Australia} = this.state;
console.log(World, Afghanistan, USA, Australia)
你可以做这样的事情,先.then after fetch for
两个请求,然后在主 .then
中的数组中获取结果
Promise.all([
fetch(
"https://example.com/reviews/",
requestOptionsDoc
).then((res1) => res1.json()),
fetch(
"https://example.com/reviews/",
requestOptionsRel
).then((res2) => res2.json()),
])
.then(([result1, result2]) => {
if (result1.detail) {
setDoctorReviewDetails("No review found.");
} else {
setDoctorReviewDetails(result1.data.comment);
}
if (result2.detail) {
setRelativeReview("No review found.");
} else {
setRelativeReview(result2.data.comment);
}
})
.catch((error) => console.log("error", error));
我想知道如何一次获取多个 GET URL,然后将获取的 JSON 数据放入我的 React DOM 元素中。
这是我的代码:
fetch("http://localhost:3000/items/get")
.then(function(response){
response.json().then(
function(data){
ReactDOM.render(
<Test items={data}/>,
document.getElementById('overview')
);}
);
})
.catch(function(err){console.log(err);});
但是,我想从我的服务器获取额外的 JSON 数据,然后使用传递给它的所有这些 JSON 数据呈现我的 ReactDOM。例如:
ReactDOM.render(
<Test items={data} contactlist={data2} itemgroup={data3}/>,
document.getElementById('overview')
);
这可能吗?如果不是,还有什么其他解决方案可以将多个 JSON 数据提取到我的渲染 ReactDOM 元素中?
使用 Promise.all
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) 的某些实现一次发出多个请求,然后对您的数据执行您想要的操作:
Promise.all([
fetch("http://localhost:3000/items/get1"),
fetch("http://localhost:3000/items/get2"),
fetch("http://localhost:3000/items/get3")
]).then(allResponses => {
const response1 = allResponses[0]
const response2 = allResponses[1]
const response3 = allResponses[2]
...
})
您可以依靠 Promises 在您决定之前执行所有这些操作。如果你习惯了jQuery,你也可以使用jQuery Promises。
在 Promise.all 中,您将强制完成每个请求,然后再继续执行代码
Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]).then(([items, contactlist, itemgroup]) => {
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}).catch((err) => {
console.log(err);
});
但即便如此,fetch 并没有在今天的所有浏览器中实现,所以我强烈建议您创建一个额外的层来处理请求,在那里您可以调用 fetch 或使用回退,假设 XmlHttpRequest
或 jQuery
ajax.
除此之外,我强烈建议您查看 Redux
来处理 React 容器上的数据流。设置会更复杂,但将来会有回报。
2018 年 8 月更新 async/await
截至今天,fetch 已在所有最新版本的主要浏览器中实现,除了 IE11,包装器仍然有用,除非你为它使用 polyfill。
然后,利用更新和现在更稳定的 javascript 功能,如解构和 async/await,您也许可以对同一问题使用类似的解决方案(请参阅下面的代码)。
我相信,尽管乍一看似乎代码多了一点,但实际上是一种更简洁的方法。希望对你有帮助。
try {
let [items, contactlist, itemgroup] = await Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]);
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}
catch(err) {
console.log(err);
};
我需要 json 格式响应,所以我自己添加了一些代码
Promise.all([
fetch(url1).then(value => value.json()),
fetch(url2).then(value => value.json())
])
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
以下是我如何获取多个端点的示例,这可能会对某人有所帮助
const findAnyName = async() => {
const urls = ['https://randomuser.me/api/', 'https://randomuser.me/api/'];
try{
let res = await Promise.all(urls.map(e => fetch(e)))
let resJson = await Promise.all(res.map(e => e.json()))
resJson = resJson.map(e => e.results[0].name.first)
console.log(resJson)
}catch(err) {
console.log(err)
}
}
findAnyName()
Here is a complete example you can check on JSFiddle
或者试试这个:将所有 URL 声明为数组。我们将遍历这个 数组并引用单个 URL 作为数组索引。
constructor(props) {
super(props);
this.state = { World: [], Afghanistan: [], USA: [], Australia: [] };
}
const urls = [
'https://corona.lmao.ninja/v2/all',
'https://corona.lmao.ninja/v2/countries/afghanistan',
'https://corona.lmao.ninja/v2/countries/usa',
'https://corona.lmao.ninja/v2/countries/australia'
];
Promise.all(urls.map(url =>
fetch(url)
.then(checkStatus) // check the response of our APIs
.then(parseJSON) // parse it to Json
.catch(error => console.log('There was a problem!', error))
))
.then(data => {
// assign to requested URL as define in array with array index.
const data_world = data[0];
const data_af = data[1];
const data_usa = data[2];
const data_aus = data[3];
this.setState({
World: data_world,
Afghanistan: data_af,
USA: data_usa,
Australia: data_aus
})
})
function checkStatus(response) {
if (response.ok) {
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
}
function parseJSON(response) {
return response.json();
}
结果
const { World, Afghanistan, USA, Australia} = this.state;
console.log(World, Afghanistan, USA, Australia)
你可以做这样的事情,先.then after fetch for 两个请求,然后在主 .then
中的数组中获取结果 Promise.all([
fetch(
"https://example.com/reviews/",
requestOptionsDoc
).then((res1) => res1.json()),
fetch(
"https://example.com/reviews/",
requestOptionsRel
).then((res2) => res2.json()),
])
.then(([result1, result2]) => {
if (result1.detail) {
setDoctorReviewDetails("No review found.");
} else {
setDoctorReviewDetails(result1.data.comment);
}
if (result2.detail) {
setRelativeReview("No review found.");
} else {
setRelativeReview(result2.data.comment);
}
})
.catch((error) => console.log("error", error));