关于promise,以及请求优化

fetch请求的三种版本优化

一、未优化版本

//发送网络请求---使用fetch发送
fetch(`/api1/search/users2?q=${
      
      keyWord}`).then(
	response => {
    
    
		console.log('联系服务器成功了');
		return response.json()
	},
	error => {
    
    
		console.log('联系服务器失败了',error);
		//返回一个新的promise实例防止继续下走,结束下面的then
		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

//await只等返回成功的值,并且后面必须跟promise实例,如果需要抛出错误,则用try{} catch(){}
try{
    
    
	const response = await fetch(`/api1/search/users2?q=${
      
      keyWord}`)
	const data = await responese.json();
	console.log(data);
}catch (error) {
    
    
	console.log('请求出错了',error);
}

//找到与此函数最近的函数加上async,这里是search函数
// search = async()=>{
    
    
	//const response = await fetch(`/api1/search/users2?q=${keyWord}`)
	//const data = await responese.json()
//}

猜你喜欢

转载自blog.csdn.net/luofei_create/article/details/116355491