javascript - 如何将两个 fetch 请求合并到同一个数组中?
问题描述
我试图在一次调用中组合两个获取请求,以便我可以在同一个数组中获取所有数据。
我已经尝试过 Promise.all 方法,但我不知道这是否是正确的方法。
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
//const api_call = await
const promises = await Promise.all([
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${API_KEY}`),
fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&APPID=${API_KEY}`)
])
const data = promises.then((results) =>
Promise.all(results.map(r => r.text())))
.then(console.log)
该代码实际上有效,我正在取回数据,但我无法理解 json 响应。
(2) ["{"coord":{"lon":-5.93,"lat":54.6},"weather":[{"id"…7086601},"id":2655984,"name":"Belfast","cod":200}", "{"cod":"200","message":0.0077,"cnt":40,"list":[{"d…on":-5.9301},"country":"GB","population":274770}}"]
我应该如何设置状态?我的状态是这样设置的,只有一个调用。
if (city) {
this.setState({
temperature: data[0].main.temp,
city: data[0].name,
有更好的方法吗?
解决方案
我会做:
getWeather = async (e) => {
e.preventDefault();
const fetchText = url => fetch(url).then(r => r.json()); // 1
const /*2*/[weather, forecast] = /*3*/ await Promise.all([
fetchText(`.../weather`),
fetchText(`.../forecast`)
]);
this.setState({ temperature: weather.temp, /*...*/ });
}
1:通过使用小助手,您不必调用Promise.all
两次。有了这个,两个请求都是并行完成的(你应该使用.json()
你想解析为 JSON 的方式)。
2:通过数组解构可以轻松取回promise结果。
3:通过await
ing 你从async
函数中获得实际好处:你不需要嵌套.then
链
推荐阅读
- javascript - 将两个元素链接在一起,因此更改一个元素的内容会自动更改另一个 Javascript/Angular 的内容
- machine-learning - 训练模型时拥有多个指标有什么作用?
- python - ModuleNotFoundError:没有名为“gnuradio”的模块
- php - Laravel:Auth::user()->id 试图获取非对象的属性“名称”
- javascript - 无法在 Safari 中使用 text()、json()、arrayBuffer() 等请求函数
- python - “如果有”函数不会检查列表中的字符串是否与用户输入匹配。Python
- javascript - 如何修复:未捕获的 ReferenceError:Jquery 中未定义模块
- c++ - 显示函数的枚举值
- c - 为什么我的 gcc 编译器不能识别 bzip2 函数,但允许我包含它们所属的库?
- python - 在一个程序中多次运行 multiprocessing Pool.map 最终会阻塞