Asher Chee YiLiang
Asher Chee YiLiang

Reputation: 57

Dojo deferred retry until success

I have a method in my dojo class which makes a request (say, a JSON one). If it succeeds, well and good. However, if it fails (times out or whatever), I want it to try again until it succeeds. To do this, I call the method itself in the error callback:

doReq: function(){
    var req = Request(...);
    return req.then(function(response, io){
        // Success!
    }, dojo.hitch(this, function(error, io){
        this.doReq(); // Failed; try again.
    }));
}

Am I doing this correctly?

Upvotes: 1

Views: 340

Answers (2)

Suttikeat Witchayakul
Suttikeat Witchayakul

Reputation: 187

I'm not sure why you return req.then(...), this will return new promise not the req's promise.

But if you want the caller of doReq to get response when the req succeeds, you can do it like this.

_request: function (deferred) {
    var req = Request(...);
    req.then(dojo.hitch(this, function (response, io) {
        // Success!
        deferred.resolve(response);
    }), dojo.hitch(this, function (error, io) {
        this._request(deferred); // Failed; try again.
        // use deferred.reject('some error message'); to reject when it reached the retry limit, if you want to.
    }));
}, 
doReq: function () {
    var deferred = new Deferred(); // from module "dojo/Deferred"
    this._request(deferred);
    return deferred.promise;
}

This is how to use it.

var thePromise = this.doReq();
thePromise.then(dojo.hitch(this, function (response) {
    console.log('response: ', response); // your response from deferred.resolve(response);
}), dojo.hitch(this, function (error) {
    console.log('error: ', error); // your error from deferred.reject('some error message'); if you have.
}));

Upvotes: 0

soeik
soeik

Reputation: 925

It can be done this way, but you may want to limit attempts,

for example:

doReq: function(attempts){
    attempts -= 1;
    var req = Request(...);
    return req.then(function(response, io){
        // Success!
    }, dojo.hitch(this, function(error, io){
        if (attempts > 0) this.doReq(attempts); // Failed; try again.
        else //return some error here
    }));
}

Upvotes: 1

Related Questions