使用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();
		});
	}
}

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

你可能感兴趣的:(日志,javascript)