1

I'm using Nodejs and Q to run a sequence of asynchronous functions. If one fails i'd like to run another function and then start the sequence again. Heres it is as is:

var promise = database.getUserCookies(user)
    .then(function (data){
        return proxy.search(data);
    })
        .fail(function (data) {
            if (data.rejected === 302) {
                var relogin = database.fetchAuth(data)
                    .then(function (data) {
                        return proxy.login(data)
                    })
                    .then(function (data){
                        return database.saveCookies(data);
                    })
                    .then(function (data){
                        //Restart the promise from the top.
                    })
            }
        })
    .then(function (data){
        return responser.search(data);
    })
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dustin Silk
  • 4,320
  • 5
  • 32
  • 48

1 Answers1

10

You need to wrap it in a function that you can call again. A promise by itself cannot be "restarted".

var promise = (function trySearch() {
    return database.getUserCookies(user)
    .then(proxy.search)
    .fail(function(err) {
        if (err.rejected === 302) { // only when missing authentication
            return database.fetchAuth(data)
//          ^^^^^^
            .then(proxy.login)
            .then(database.saveCookies)
            .then(trySearch) // try again
        } else
            throw err;
    })
}())
.then(responser.search)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375