Skip to content

Instantly share code, notes, and snippets.

@ericzon
Last active August 2, 2016 15:00
Show Gist options
  • Save ericzon/14fc05cde7f9877377a29228c4473b64 to your computer and use it in GitHub Desktop.
Save ericzon/14fc05cde7f9877377a29228c4473b64 to your computer and use it in GitHub Desktop.
Example of Retrying promise n times with timeout (not tested yet!) (Idea taken from http://stackoverflow.com/questions/21146856/using-the-q-implementation-in-angular-how-can-i-loop-a-promise-until-success)
var express = require('express');
var app = express();
var q = require('q');
function retryingPromise(fn, cfg, times) {
var counter = 0;
var delay = 0;
var _times = times ? times : 2;
var _step = _step ? step : 1000;
var _cfg = cfg ? cfg : {};
var deferred = q.defer();
var makeRequest = function (__cfg) {
var args = arguments;
counter++;
delay += _step;
var self = this;
fn(__cfg).then(function(result) {
deferred.resolve(result);
}, function(e) {
if(counter >= _times) {
console.log("DEBUG retryPromise fails with counter (",counter,") and error: ", e);
return deferred.reject(e);
}
setTimeout(function() {
makeRequest.apply(self, args);
}, delay);
});
};
makeRequest(_cfg);
return deferred.promise;
}
function dummyPromise(opts) {
if(opts.id < 4) {
return q.reject("ko");
} else {
return q.when("ok");
}
}
app.get('/test-promise', function(req, res, next) {
var params = req.query;
console.log("get /test-promise con params: ", params);
retryingPromise(dummyPromise, {id: params.id}, 4).then(function(r) {
console.log("DEBUG dummyPromise ok -> ", r);
res.end(r);
}).catch(function(e) {
console.log("DEBUG dummyPromise catch! ", e);
res.status = 500;
res.end(e);
});
});
var server = app.listen(5000, function() {
var port = server.address().port;
console.log("Server running on port: ",port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment