有一个ajax请求需要在三个ajax请求之后发起,其中之前的三个ajax可以并行,如何优雅的实现这种写法?

我有一个接口,需要在三个接口都调用成功之后执行,不知道怎么写

阅读 6.7k
5 个回答

用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("&");
    }
  // 用并行
    Promise.all([ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}),ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"})]).then(function(allres){
    console.log(allres);//三个请求的返回的集合
     ajax('POST','./1.php',{XXXX}).then();
        
    })

$.when , jQuery 的 API 。

如用了jQuery 1.6+,可以用jQuery延迟函数

$.when($.get('/a'),$.get('/b'),$.get('/c')).then(function(a,b,c){
    return $.get('/d',{a:a,b:b,c:c})
}).then(function(d){
    console.log(d)
})

如果不考虑兼容或已引用polyfill,则建议用Promise

// ajax_X 是一个返回promise对像的函数,jQuery 延迟对像也是可以的
Promise.all([ajax_a(),ajax_b(),ajax_c()])
    .then(([a,b,c])=>ajax_d({a,b,c}))
    .then(d=>console.log(d))

用promise.all就可以了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进