fetch请求的三种版本优化
一、未优化版本
fetch(`/api1/search/users2?q=${
keyWord}`).then(
response => {
console.log('联系服务器成功了');
return response.json()
},
error => {
console.log('联系服务器失败了',error);
return new Promise(()=>{
})
}
).then(
response => {
console.log('数据返回成功了',response);},
error => {
console.log('数据返回失败了',error);}
)
二、优化版本1
fetch(`/api1/search/users2?q=${
keyWord}`).then(
response => {
console.log('联系服务器成功了');
return response.json()
}
).then(
response => {
console.log('数据返回成功了',response);},
).catch(
error => {
console.log('请求出错了',error);}
)
三、优化版本2
try{
const response = await fetch(`/api1/search/users2?q=${
keyWord}`)
const data = await responese.json();
console.log(data);
}catch (error) {
console.log('请求出错了',error);
}