您的位置:首页 > 其它

用Promise实现两个Ajax有序进行

2018-03-25 21:33 246 查看
作为前端面试中一道高命中率的题,啥也不说直接上代码:var getJSON = function(url,callback){
var promise = new Promise(function (resolve,reject) {
var client = new XMLHttpRequest();
client.open("GET",url);
client.onreadystatechange = handler;//readyState属性的值由一个值变为另一个值时,都会触发readystatechange事件
client.responseType = "json";
client.setRequestHeader("Accept","application/json");
client.send();

function handler(){
if(this.readyState !== 4){
return;
}
if(this.status === 200){
callback(this.response);
resolve(this.response);
}else{
reject(new Error(this.statusText))
}
};
});
return promise;
};

getJSON("./e2e-tests/get.json",function(resp){
console.log("get:" + resp.name);
}).then(function (json) {
getJSON("./e2e-tests/get2.json",function(resp){
console.log("get2:" + resp.name);
})
}).catch(function (error) {
console.log("error1:"+error);
})主要思想就是运用Promise中的then方法。
另注:getJSON函数里面的url是相对于当前html页面的相对路径。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐