Multiple ajax calls from array and handle callback when completed

前端 未结 2 464
别那么骄傲
别那么骄傲 2020-12-05 02:58

I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.

2条回答
  •  醉酒成梦
    2020-12-05 03:44

    The arguments to $.when should be the return value of $.ajax, which also doesn't need to be called separately -- that makes no sense. You want something like this:

    for (i = 0; i < list.length; i++) {
       requests.push($.ajax(...));
    }
    $.when.apply(undefined, requests).then(...)
    

    The reason that .apply is needed is because $.when can take multiple arguments, but not an array of arguments. .apply expands essentially to:

    $.when(requests[0], requests[1], ...)
    

    This also assumes that the requests can be completed in any order.

    http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.

提交回复
热议问题