Skip to content

Instantly share code, notes, and snippets.

@apkostka
Created February 12, 2014 01:35
Show Gist options
  • Save apkostka/8948323 to your computer and use it in GitHub Desktop.
Save apkostka/8948323 to your computer and use it in GitHub Desktop.
Wait for multiple AJAX calls using jQuery
/* 'promises' can be thought of as an array of eventual values, and
* calling '.then()' of any one of those values would allow us to execute some event once the value
* has been fulfilled, i.e. once our AJAX call has provided us with a response.
*
* By calling 'apply()' on '$.when', we can call 'then()' for all members of promises, meaning we
* can wait until each call has been completed and a value has been returned.
*/
var promises = [
$.ajax('http://api.endpoint.com?type=data1'),
$.ajax('http://api.endpoint.com?type=data2')
];
$.when.apply($, promises).then(function(data1, data2){
console.log(this, data1, data2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment