【发布时间】:2019-02-17 08:56:00
【问题描述】:
我正在用 JavaScript 编写天气应用程序,你可以猜到有很多 API 请求。所以在这里我向 API 发出请求,然后它将返回我的城市图像。城市来自用户输入。
async getCityImage(city) {
console.log(city, 'getCityImage');
await fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`)
.then(res => res.json())
.then((res) => {
this.imageUrl = res.photos[0].image.mobile;
});
}
}
问题是用户输入可能不合适,当然 API 会返回这样的错误
> GET https://api.teleport.org/api/urban_areas/slug:munchen/images/ 404
(未找到)
For example there are some cities which names are separated by hyphen
坎萨斯城、危地马拉城等......
所以我想处理错误,以便错误不会影响 UI,但是发出另一个这样的请求,然后返回答案`
GET https://api.teleport.org/api/urban_areas/slug:${city}-city/images/
当时我试图通过嵌套请求来实现它,但它不起作用
【问题讨论】:
-
请告诉我们您尝试了什么。
标签: javascript error-handling promise async-await fetch