promise封装AJAX,既可用callback也可用.then(较新版的jquery也是如此)

知识点

onreadystatechange和onload使用时的区别。

onreadystatechange是状态发生变化时触发,包括status,readyState都会触发
onload知识readyState===4就触发。也就是不论是否请求是否成功segmentfault

//普通callbackpromise

//封装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封装url

//封装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)
})

结论

是用promisecode

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);    
})
相关文章
相关标签/搜索