web前端界面加载过程中,需要进行对某个数组中的每个对象逐个进行ajax调用,从后台获取该对象的更多详情属性:
for (i in array)
{
ajax()
}
这样的场景可以用promise么?请大神给建议!
web前端界面加载过程中,需要进行对某个数组中的每个对象逐个进行ajax调用,从后台获取该对象的更多详情属性:
for (i in array)
{
ajax()
}
这样的场景可以用promise么?请大神给建议!
function ajax(mode,url,data){
return new Promise(function(resolve,reject){
var request = new XMLHttpRequest();
request.open(mode,url,true);
console.log(postDataFormat(data))
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
request.send(postDataFormat(data));
request.onload = function(){
if((this.status >= 200 && this.status < 300) || this.status == 304){
resolve(this);
}else{
reject(this);
};
};
})
}
function postDataFormat(obj){
if(typeof obj != "object" ) {
alert("输入的参数必须是对象");
return;
}
var arr = new Array();
var i = 0;
for(var attr in obj) {
arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
i++;
}
return arr.join("&");
}
//调用
ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}).then((res)=>{
console.log(res.response);
return ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"});
}).then((res)=>{
console.log(res.response);
}).catch((res)=>{
console.log(res.statusText);
})
//当然,也可以用并行
Promise.all([ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}),ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"})]).then(function(allres){
console.log(allres);
})
可以,类似于
这样then里的res就是所有的ajax的结果数组
Promise.all()