常见fetch用法如下:
fetch(url).then(response => {
return response.json()
}).then(res => {
console.log(res)
})
把以上promis形式改成async和await形式
const fetchAPI = async () => {
const response = await fetch(url)
const data = await response.json()
console.log(data)
}
fetchAPI()
添加异常处理
const fetchAPI = async () => {
const response = await fetch(url)
if(response.status===200){
const data = await response.json()
console.log(data)
}else{
console.log('请求异常')
}
}
fetchAPI()
加上try/catch
const fetchAPI = async () => {
try {
const response = await fetch(url)
if (response.status === 200) {
const data = await response.json()
console.log(data)
} else {
console.log('请求异常')
}
} catch (err) {
console.log(err)
}
}
fetchAPI()