鍍金池/ 問答/HTML/ vue.js中如何用promise實(shí)現(xiàn)for循環(huán)ajax調(diào)用?

vue.js中如何用promise實(shí)現(xiàn)for循環(huán)ajax調(diào)用?

web前端界面加載過程中,需要進(jìn)行對某個(gè)數(shù)組中的每個(gè)對象逐個(gè)進(jìn)行ajax調(diào)用,從后臺獲取該對象的更多詳情屬性:
for (i in array)
{

ajax()

}

這樣的場景可以用promise么?請大神給建議!

回答
編輯回答
默念

前后請求是否對返回的數(shù)據(jù)有依賴

2018年4月4日 23:26
編輯回答
澐染

可以用,如果你獲取的數(shù)據(jù)之間沒有關(guān)聯(lián)的話,在ajax返回后對array[i]里面的數(shù)據(jù)進(jìn)行擴(kuò)充。
tips:注意一下在異步過程中捕獲正確的i值。

2017年10月22日 11:35
編輯回答
乞許

可以,類似于

let proArr = [];
for(i in array){
    proArr.push(new Promise(ajax()))
}
Promise.all(proArr).then(res=>{...}).catch(...)

這樣then里的res就是所有的ajax的結(jié)果數(shù)組
Promise.all()

2017年6月10日 11:09
編輯回答
帥到炸
    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("輸入的參數(shù)必須是對象");
          return;
      }
          var arr = new Array();
          var i = 0;
          for(var attr in obj) {
              arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
              i++;
          }
          return arr.join("&");
    }
    //調(diào)用
    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);
    })
    //當(dāng)然,也可以用并行
    Promise.all([ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}),ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"})]).then(function(allres){
        console.log(allres);
    })
2018年6月17日 07:40