一,封装AJAX,既可用callback也可用.then(较新版的jquery也是如此)
知识点
onreadystatechange和onload使用时的区别。
onreadystatechange是状态发生变化时触发,包括status,readyState都会触发
onload知识readyState===4就触发。也就是不管是否请求是否成功
//普通callback
//封装get
function doGet(url,callback,aynsc){
let xhr = new XMLHttpRequest();
xhr.open(url,"get",aynsc===true?true:false);
xhr.onreadystatechange=function(){
if(status===200&&readyState===4){
callback(xhr.responseText);
}
}
xhr.send(null);
}
//使用
doGet("https://segmentfault.com/write?freshman=1",function(){
console.log(data)
})
//promise封装
//封装get
function doGet(url,callback,aynsc){
return new Promise(function(resolved,rejected){
new XMLHttpRequest();
xhr.open(url,"get",aynsc===true?ture:false);
xhr.send(null);
xhr.onload=function(){
resolved(xhr.responseText)
//兼容普通回调
callback&&callback(xhr.responseText);
};
xhr.onerror=function(err){
rejected(err)
//兼容普通回调
callback&&callback(err);
}
})
}
//使用方式一
doGet("https://segmentfault.com/write?freshman=1",function(){
console.log(data)
})
//使用方式二
doGet("https://segmentfault.com/write?freshman=1").then(function(data){
console.log(data)
}).catch(fucntion(err){
console.log(err)
})
结论
是用promise
doGet("https://segmentfault.com/write?freshman=1")
.then(function(data){
console.log(data); //data第一个请求结果
return doGet("https://segmentfault.com/write?freshman=2");
}).then(function(data){
console.log(data) //data第二个请求结果,这里没办法拿到第一个请求结果,除非在外面用个变量接收
})
//不需要在外面引入变量接收(所有实例promise的peending都是fulfilled,all()的resolved才进入,只要有一个是rejected就会进入rejected)
let allPromise = Promise.all(doGet("https://segmentfault.com/write?freshman=1"),doGet("https://segmentfault.com/write?freshman=2"));
allPromise
.then(function(data){
console.log(data) //[第一个请求结果,第二个请求结果]
})
.catch(function(err){
console.log(err);
})
二,promise结合setTimeout,实现间隔输出
for (let i=0; i<5; i++) {
new Promise(res => {
setTimeout(()=>{
console.log(i)
res()
}, 1000*i)
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。