使用Promise封装ajax

基于原生js封装ajax(回调函数)

//封装ajax
const $ = {
	//get请求
	get:function(url,fn){
 		let xhr = new XMLHttpRequest();
 		xhr.open('get',url,true);
 		xhr.onreadystatechange=function(){
 			if(xhr.readyState===4&&xhr.status===200){
 				fn(xhr.responseText);
 			}
 		}
 		xhr.send();
 	}
}

使用回调函数的写法发送请求
此时,我们希望第一个请求响应后,紧接着发送第二个请求,此时代码就会出现嵌套。(那么如果有更多的请求,嵌套...

$.get('http://127.0.0.1:3000/users',function(users){
	$.get('http://127.0.0.1:3000/codes',function(codes){
		console.log(users,codes)
	});
})

在原有的基础上使用Promise封装

// 使用Promise封装ajax
const $ = {
	get:function(url){
		return new Promise(function(resolve,reject){
			let xhr = new XMLHttpRequest();
			xhr.open('get',url,true);
			xhr.onreadystatechange=function(){
				if(xhr.readyState===4&&xhr.status===200){
					// fn(xhr.responseText);//不再需要回调函数
					// 成功直接使用resolve
					resolve(xhr.responseText);
				}
			}
			xhr.send();
		});
	}
}

使用了Promise封装的写法发送请求
代码结构更加清晰明了,Jquery中的ajax早已支持Promise的写法

let data = {};//定义变量保存数据
$.get('http://127.0.0.1:3000/users')
	.then(function(users){
		data.users=JSON.parse(users);
		return 	$.get('http://127.0.0.1:3000/codes');
	}).then(function(codes){
		data.codes=JSON.parse(codes);
	});
console.log(data);

回调函数(callback)与Promise的结合

// 兼容Promise与callback的ajax
const $ = {
	get:function(url,fn){
		return new Promise(function(resolve,reject){
			let xhr = new XMLHttpRequest();
			xhr.open('get',url,true);
			xhr.onreadystatechange=function(){
				if(xhr.readyState===4&&xhr.status===200){
					fn && fn(xhr.responseText);//需要回调函数
					// 成功直接使用resolve
					resolve(xhr.responseText);
				}
			}
			xhr.send();
		});
	}
}

以上两种方式结合就可以适应不同的使用习惯了😀

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值