用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页面的相对路径。
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页面的相对路径。
相关文章推荐
- 实现两个有序单链表的合并。要求:随机创建两个单链表,实现单链表的排序,再对两个有序单链表进行合并。
- C语言实现:合并两个有序的数组,合并后的数组依然有序
- C++实现打印两个有序链表公共部分的方法
- 将两个递增的有序链表合并为一个递增的有序链表(C语言编程实现)
- springmvc+spring+mybatis+maven+mysql项目(二)Springmvc + ajax 实现javaweb验证码的制作及进行异步验证
- 使用Ajax实现DropDownList和ListBox的联动以及两个ListBox之间数据的移动
- Ajax 实现对查询出的表单进行删除/修改
- 4:如何实现对两个整数变量的值进行互换。
- 已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序,要求用递归方法进行。
- 编程实现合并两个有序单链表
- Java实现两个有序的单项链表的合并
- 将两个非递减的有序链表合并为一个非递增的有序链表(C语言编程实现)
- 编写函数实现对两个变量的值进行交换
- 用有名管道实现文件复制,有两个终端 ,一个进行复制操作,另一个进行粘贴操作
- Java实现合并两个有序序列算法示例
- 探讨:将两个链表非降序合并为一个链表并依然有序的实现方法
- 实现两个有序链表的合并
- 使用 AJAX,局部刷新 GridView 进行数据绑定的简单实现
- 将两个非递减的有序链表合并为一个非递增的有序链表(C语言编程实现)