weixin_33716941 2017-08-23 20:53 采纳率: 0%
浏览 30

如何清理AJAX回调

I'd like to make an API call that prints out the values retrieved from 2 helper API calls.

See:

function api_call() {
  $.ajax({
      url: "...", 
      success: function (objects) {
          for (var i = 0; i < objects.length; i++) {
              var id_1 = api_helper1(objects[i].id_1);
              var id_2 = api_helper2(objects[i].id_2);

              console.log(id_1 + id_2);
          }
      }
  });
}

function api_helper1(id_1) {
  $.ajax({
      url: "...", 
      success: function (value) {
          return value;
      }
  });
}

function api_helper2(id_2) {
  $.ajax({
      url: "...", 
      success: function (value) {
          return value;
      }
  });
}

The issue here is AJAX is async so api_helper1 and api_helper2 will run before console logs id_1 + id_2. What is the cleanest way to accomplish this without having multiple AJAX calls inside each other's success function?

  • 写回答

2条回答 默认 最新

  • weixin_33747129 2017-08-23 21:01
    关注

    You can do this with Promises:

    function api_call() {
      return $.ajax({
          url: "...",
      });
    }
    
    function api_helper1(id_1) {
      return $.ajax({
          url: "..."
      });
    }
    
    function api_helper2(id_2) {
      return $.ajax({
          url: "..."
      });
    }
    
    api_call().done((objects)=>{
        for (var i = 0; i < objects.length; i++) {
            $.when(api_helper1(objects[i].id_1), api_helper2(objects[i].id_2)).then((id_1, id_2)=>console.log(id_1 + id_2));
        }
    })
    
    评论

报告相同问题?