等待所有 ajax 請求完成

用 jQuery 實現 promise,待所有 ajax 執行完後才執行指定操作

notice: 所有 ajax call 為非同步執行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function demonstrate() {
var urls = ["url_1", "url_2", "url_3"];

callAjaxRequsts(urls)
.done(function() {
console.log("all done");
})
.fail(function() {
console.log("error");
});
}

function callAjaxRequsts(urls) {
var requests = $.map(urls, function(value, index) {
return $
.ajax({
url: value,
type: "post"
})
.done(function(response) {
console.log(response);
});
});

return $.when.apply($, requests);
}

Reference

https://stackoverflow.com/questions/23300168/deferred-promise-ajax-loop-then-never-happens
https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done