I’ve got some code set up, and I’d like to get a very simple API going for ajax requests.
So, what I’d like to do is simply do is use deferred somehow to return success.
var factory = function(dataParams) {
return $.ajax({
type : "POST",
dataType : "json",
url : "http://example.com/whatever",
data : dataParams,
beforeSend : function(jqXHR, settings){/*... something here ...*/},
error : function(jqXHR, textStatus, errorThrown){/*... something here ...*/},
complete : function(jqXHR, textStatus) {/*... something here ...*/}
});
Which would get called by something such as
var dataTools = {
"foo" : function(){
factory({"One": 1}).success(function(jqXHR){
//Do something to jqXHR
//Return something to the "upper most" calling... how?
})
}
"bar" : function(){
factory({"Two": 2}).success(function(jqXHR){
//Return jqXHR to the "upper most" calling... how?
})
}
};
Such that I could use it in this way:
$.each(dataTools.foo(), function(k,v){
console.log(v);
});
Basically, the object dataTools.foo returns a value from success, or, should return an empty set in the vent of a failure, or something that skips that code branch.
I’ve attempted using $.when().then(), but I can’t seem to figure out how to fit that into something like I’ve described here.
Ajax is asynchronous.
You cannot use a
$.eachon an asynchronous function.You cannot have a function calling a function calling ajax then expect to use
$.whenand the related functions.You need to do something like is said in the doc
Try something like this: