Skip to content

Instantly share code, notes, and snippets.

@terrymun
Created March 27, 2015 05:12
Show Gist options
  • Save terrymun/b5deba872cdb459f0ce0 to your computer and use it in GitHub Desktop.
Save terrymun/b5deba872cdb459f0ce0 to your computer and use it in GitHub Desktop.
Better $.ajax requests—returning the promise/deferred object
// Generic function to make an AJAX call
var fetchData = function(query, dataURL) {
// Return the $.ajax promise
return $.ajax({
data: query,
dataType: 'json',
url: dataURL
});
}
// Make AJAX calls
// 1. Get customer order
// 2 Get customer ID
var getOrder = fetchData(
{
'hash': '2528ce2ed5ff3891c71a07448a3003e5',
'email': 'john.doe@gmail.com'
}, '/path/to/url/1'),
getCustomerID = fetchData(
{
'email': 'john.doe@gmail.com'
}, '/path/to/url/2');
// Use $.when to check if both AJAX calls are successful
$.when(getOrder, getCustomerID).then(function(order, customer) {
console.log(order.data);
console.log(customer.data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment