Skip to content

Instantly share code, notes, and snippets.

@rattanchauhan
Created May 30, 2017 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattanchauhan/f22b82359be26f22377f60aa1025ae9e to your computer and use it in GitHub Desktop.
Save rattanchauhan/f22b82359be26f22377f60aa1025ae9e to your computer and use it in GitHub Desktop.
Extjs Poller utility
Ext.define('Empty.common.Poller', {
singleton: true,
alternateClassName: ['Poller'],
/**
* Utility to poll an endpoint provided with the required parameters
* Mandatory parameters are : params.pollInterval, params.pollTimeout, params.success
* @params {Object} params
*
*/
poll: function (params) {
var url = params.url,
pollInterval = params.pollInterval,
pollTimeout = params.pollTimeout,
success = params.success,
failure = params.failure,
endTime = Number(new Date()) + pollTimeout*1000;
if(!pollInterval || !pollTimeout || !success) {
console.log('Mandatory parameters are missing for starting polling. Please provide [pollInterval, pollTimeout, success] ');
return;
}
if(success && !Ext.isFunction(success)) {
console.warn('success ');
success = function () {};
}
if(failure && !Ext.isFunction(failure)) {
failure = function () {};
}
(function p() {
Ext.Ajax.request({
url: url + '?_dc=' + (new Date()).getTime(),
failure: function (response, operation) {
console.log("Lookup Response failure callback");
console.dir(response);
console.dir(operation);
failure();
},
success: function (response, operation) {
if (response.status === 204) {
if (Number(new Date()) > endTime) {
console.log('Client timeout occurred!! Stopping polling routine ....');
failure(new Error('Failed due to client timeout..'), true);
} else {
// keep polling until data is received or timeout occurs
console.log('Data not received yet. Scheduling next poll after ' + pollInterval + ' seconds...');
setTimeout(p, pollInterval*1000);
}
} else {
var data = response.responseText ? Ext.JSON.decode(response.responseText) : null;
if (data) {
success(data);
} else {
failure(new Error('HTTP OK returned from server but no data received.. Stopping polling.'), false);
}
}
}
});
})();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment