I am working on my scripts for ReST API processes. Now I need a function which keeps retrying to request to the API as many as possible in few seconds.
So I wrote some Promise abstractions and I made something like below:
$(function () {
var $el = $('#test');
function api (message) {
return $.ajax('/echo/json/', {
method: 'POST',
data: { json: JSON.stringify({ message: message }), delay: 2000 },
timeout: 1000
});
}
// Process to keep retrying an API request as many as possible in 3 seconds
retried(_.bind(api, undefined, 'Hello, world.'), 3000)
.then(function (dat) {
$el.text(dat.message);
}, function (err) {
if (err instanceof Error) $el.css('color', 'red');
$el.text(err.message);
});
});
Some functions I made for the above are below:
// Promise wrapper
var promisify = function (func) {
var funcPartial = function () {
var funcArgs = _.toArray(arguments);
var dfr = new $.Deferred(), promiseArgs = [ dfr.resolve, dfr.reject ];
var timeoutId = setTimeout(function () {
clearTimeout(timeoutId);
func.apply(undefined, _.union(promiseArgs, funcArgs));
}, 1);
return dfr.promise();
};
return funcPartial;
};
// Promise abstraction for recursive call
retried = promisify(function (resolve, reject, done, duration, start) {
if (!_.isNumber(start)) start = +(new Date());
return done()
.then(resolve, function (err) {
var stop = +(new Date());
if (duration <= stop - start) {
reject(err);
} else {
return retried(done, duration, start);
}
});
});
The process finishes in a correct condition, but the retried
function won't return Promise chain.
I am really stacked. Can someone point me out the wrong points to correct the implementation above?
Here's the entire demo script.
Thank you.
SOLVED
Thanks to @BenjaminGruenbaum below, I have just noticed that I did not need promisify
to make retried
function at all. This was completely shame question, but thanks again to all the people replied on this question.
This is revised retried
function which does not need promisify
at all...
var retried = function (done, duration, start) {
if (!_.isNumber(start)) start = +(new Date());
return done()
.then(function (dat) {
return dat;
}, function (err) {
var stop = +(new Date());
if (duration > stop - start) return retried(done, duration, start);
return err;
});
};
I updated the demo and it works fine now XD
DEMO (revised)