欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-09 13:23:22
作为前端面试中一道高命中率的题,啥也不说直接上代码: var getjson = function(url,callback){ var promise = new pro...

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

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