javascript多个ajax调用,单个回调?

时间:2014-06-18 14:19:05

标签: javascript callback

我的第一篇文章,大家好。)

我有这个js代码来访问json api:

function a() {
    //does some things
    //...
    //then calls function b
    b(some_params);
}
function b(params) {
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        alertFunction(response);
    });
}
function alertFunction(resp) {
    console.log ("the response is: ");
    console.log(resp);
}

这工作正常,但现在我需要修改它才能执行此操作: 在函数a()中,我不需要对b()进行单次调用,而是需要在循环中多次调用b(),每次都使用不同的参数。 然后我想调用alertFunction()传递一个包含所有响应的数组,但只有在收到所有响应后才会这样。

我在查看延迟对象的一些示例后,尝试使用$ .when和.then,但它不起作用:

function a() {
    //does some things
    //...
    //then calls function b
    var allResponses = [];
    $.when(
        anArray.forEach(function(element) {
            allResponses.push(b(some_params));
        });
    ).then(function() {
        alertFunction(allResponses);
    });
}
function b(params) {
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        //alertFunction(response);
    });
    return response;
}
function alertFunction(allresp) {
    console.log ("the responses are: ");
    console.log(allresp);
}

任何帮助?

更新 - 好吧终于搞定了。我把最后的代码放在这里,以防它帮助其他人...

function a() {
    //does some things
    //...
    //then calls function b
    var requests = [];
    //-- populate requests array
    anArray.forEach(function(element) {
        requests.push(b(some_params));
    });
    $.when.apply($, requests).then(function() {
        alertFunction(arguments);
    });
}
function b(params) {
    var def = $.Deferred();
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        def.resolve(response);
    });
    return def.promise();
}
function alertFunction(allresp) {
    console.log ("the responses are: ");
    console.log(allresp);
}

1 个答案:

答案 0 :(得分:1)

以下是将$.when与未知数量的AJAX调用一起使用的一种方法:

$(function () {
  var requests = [];
  //-- for loop to generate requests
  for (var i = 0; i < 5; i++) {
    requests.push( $.getJSON('...') );
  }
  //-- apply array to $.when()
  $.when.apply($, requests).then(function () {
    //-- arguments will contain all results
    console.log(arguments);
  });
});

修改

应用于您的代码,它应该如下所示:

function a() {
    var requests = [];
    //-- populate requests array
    anArray.forEach(function(element) {
        requests.push(b(some_params));
    });
    $.when.apply($, requests).then(function() {
        alertFunction(arguments);
    });
}
function b(params) {
    //-- In order for this to work, you must call some asynchronous
    //-- jQuery function without providing a callback
    return someObject.makeajaxcalltoapi();
}
function alertFunction(allresp) {
    console.log ("the responses are: ");
    console.log(allresp);
}