So consider the following scenario:
i want to check the stock-availability of a product on multiple occasions in my ecommerce-script.
What i did was
var checkStock = function(id) {
$.ajax({
type: "POST",
dataType:'json',
url: "class/updateCart.php",
data: { productID: id, action: 'checkStock' }
}).done(function(data) {
return parseInt(data.stock);
}).fail(function(data) {
return 'AJAX FAILED';
});
}
So now i wanted to use it like this:
if(checkStock(productID) == 0) {
// do something (A)
}
this obviously did not work so on my research i came across this:
jQuery: Return data after ajax call success & How do I return the response from an asynchronous call?
with really great explanations for deferred objects / promises. But somehow i'm not able to see the difference between
var checkStock = function(id) {
$.ajax({
type: "POST",
dataType:'json',
url: "class/updateCart.php",
data: { productID: id, action: 'checkStock' }
}).done(function(data) {
// DO SOMETHING (A)
}).fail(function(data) {
// DO SOMETHING (B)
});
}
and (the deferred object way)
function checkStock() {
return $.ajax(...);
}
checkStock().done(function(result) {
// DO SOMETHING (A)
}).fail(function() {
// DO SOMETHING (B)
});
both options only allow me to DO SOMETHING (A)
everytime the function is a success. But i want to check the stock availability and do different stuff with the result.
For example somewhere in my code i do this:
if(checkStock(productID) == 0) {
// do something (A)
}
and somewhere else i do something completely different
if(checkStock(productID) > 5) {
// do something completely different
}
So my questions are:
- What's the difference between deferred objects and the simple .fail/.success-callbacks of the ajax-call?
- Is it possible to do what i want without making the ajax call synchronous? I want to use the same ajax-Call and use the result differently depending on the context where i use the ajax-call.