用Promise解决多个异步Ajax请求导致的代码嵌套问题(完美解决方案

2019-09-14 06:51:06于海丽

问题

前端小同学在做页面的时候,犯了个常见的错误:把多个Ajax请求顺序着写下来了,而后面的请求,对前面请求的返回结果,是有依赖的。如下面的代码所示:

var someData;
$.ajax({      url: '/prefix/entity1/action1',
      type: 'GET' ,
      async: true,
      contentType: "application/json",
      success: function (resp) {
        //do something on response
        someData.attr1 = resp.attr1;
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        //在这个页面里,所有的请求的错误都做同样的处理
        if (XMLHttpRequest.status == "401") {
          window.location.href = '/login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });
$.ajax({
      url: '/prefix/entity2/action2',
      type: 'POST' ,
      dataType: "json",
      data: JSON.stringify(someData),
      async: true,
      contentType: "application/json",
      success: function (resp) {
        //do something on response
       },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        //在这个页面里,所有的请求的错误都做同样的处理
        if (XMLHttpRequest.status == "401") {
          window.location.href = '/login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });

以上代码有两个问题:

*首先就是执行顺序不能保证,action2很可能在action1返回之前就发出了,导致someData.attr1这个参数没能正确传出

*其次两个ajax请求的代码重复很严重

思路

代码重复的问题相对好解决,尤其是在自己的项目里,各种参数可以通过规范定死,封装一个参数更少的ajax方法就好了
//url:地址
//data:数据对象,在函数内部会转化成json串,如果没传,表示用GET方法,如果传了,表示用POST方法
function ajax(url, data, callback) {
    $.ajax({
      url: url,
      type: data == null ? 'GET' : 'POST',
      dataType: "json",
      data: data == null ? '' : JSON.stringify(data),
      async: true,
      contentType: "application/json",
      success: function (resp) {
        callback(resp);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == "401") {
          window.parent.location = '/enterprise/enterprise_login.html';
          self.location = '/enterprise/enterprise_login.html';
        } else {
          alert(XMLHttpRequest.responseText);
        }
      }
    });
}

这样只有url,data和callback三个必要的参数要填,其他都定死了

执行顺序的问题,可以把第二个请求放在第一个请求的回调里,形如:
ajax('/prefix/entity1/action1',null, function(resp){
   //do something on response
   someData.attr1 = resp.attr1;
   ajax('/prefix/entity2/action2', someData, function(resp){
     //do something on response
   }
};