当前位置: 移动技术网 > IT编程>网页制作>CSS > 用Promise实现两个Ajax有序进行(代码教程)

用Promise实现两个Ajax有序进行(代码教程)

2019年06月02日  | 移动技术网IT编程  | 我要评论

作为前端面试中一道高命中率的题,啥也不说直接上代码:

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页面的相对路径。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网