How To Know Which $.ajax Promise Has Resolved?
I'm using jQuery ajax to request data which will then be made into different kinds of charts or tables. I've put the queries I want to run into an object and send the requests. run
Solution 1:
If you pass jQuery ajax a parameter that it knows nothing about, it ignores it and you can access it later.
Here we set a parameter for your extra value (mykey) then we have access to it later for the instance we are using:
function refreshData() {
for (var key in baseQueries) {
runQuery(baseQueries[key], key)
.done(function(data) {
console.log("Query data for " + this.myKey);
// "this" here is the ajax for which the promise (ajax) gets resolved,
// and we return that promise so it works here.
// want to call different charting functions
// based upon which results are returned
});
}
};
runQuery(obj,key) { // "public" function
var params = $.extend({}, defaults, obj);
return sendRequest(queryUrl, params,,key)
}
sendRequest(url, data, method, key) { // "private" function
method = method || "GET";
return $.ajax({
type: method,
url: url,
dataType: "json",
data: data,
myKey:key
})
.fail(function(error) {
console.log(error);
});
}
Solution 2:
if you want to check if jquery promise is resolved you can check with jqueryPromise.state() which returns either pending
, resolved
or rejected
depending on state.
If you are sending multiple ajax requests
and you want to know when they are completed you can put them into array ([$.ajax(...),$.ajax(...)]
) and pass it to
$.when like
var requests = [$.ajax(...),$.ajax(...)];
$.when.apply($, requests).done(function() {
console.log('all requests completed');
});
if you want to build something complex with promises I would suggest using bluebird or less complex rsvp
Post a Comment for "How To Know Which $.ajax Promise Has Resolved?"