Created
March 27, 2015 05:12
-
-
Save terrymun/b5deba872cdb459f0ce0 to your computer and use it in GitHub Desktop.
Better $.ajax requests—returning the promise/deferred object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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