Promises And Recurrent Ajax Calls
I am trying to come up with a function whose signature would be identical to jQuery.ajax. It is a separate function because depending on the HTTP status in the response it should e
Solution 1:
Is it possible to reuse the „thenable” object returned by the $.ajax calls, as in chaining up the promises returned by subsequent calls?
Yes and No. You would loose the multiple arguments, and there's no way to emit progress events. It would look like this:
function timeout(ms) {
var d = $.Deferred();
setTimeout(d.resolve, ms);
return d.promise();
}
function callApi(ajaxOptions) {
function tryit () {
return $.ajax(ajaxOptions).then(data) {
if (this.status == 200)
returndata;
elseif (this.status == 201 || this.status == 202)
return timeout(2000).then(tryit);
elsereturn $.Deferred().reject(this.responseText
? JSON.parse(this.responseText)
: {
title: "Couldn't contact data server.",
content: "It seems the API server is down. Please contact the DAV team."
});
});
}
return tryit();
}
How would you go about incorporating a progress call on the promise chain each time another $.ajax is called?
Just call notify
:
functioncallApi(ajaxOptions) {
var deferred = $.Deferred();
functiontryit() {
$.ajax(jqAjaxOptions).always(function() {
switch (this.status) {
case200:
return deferred.resolveWith(this, arguments);
case201:
case202:
deferred.notify("Next try in 2s");
returnsetTimeout(tryit, 2000);
default:
deferred.notify(this.responseText
? JSON.parse(this.responseText);
: {
title: "Couldn't contact data server.",
content: "It seems the API server is down. Please contact the DAV team."
});
deferred.rejectWith(this, arguments);
}
});
}
tryit();
return deferred.promise();
}
Post a Comment for "Promises And Recurrent Ajax Calls"