Restart a promise after fail

本小妞迷上赌 提交于 2019-12-04 06:20:10

问题


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);
    })

回答1:


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)


来源:https://stackoverflow.com/questions/26873048/restart-a-promise-after-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!