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);    
})
相關文章
相關標籤/搜索