【问题标题】:Restart a promise after fail失败后重新启动承诺
【发布时间】:2015-01-08 11:35:53
【问题描述】:

我正在使用 Nodejs 和 Q 来运行一系列异步函数。如果一个失败,我想运行另一个函数,然后再次启动序列。这是原样:

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

【问题讨论】:

    标签: javascript node.js promise q


    【解决方案1】:

    您需要将它包装在一个可以再次调用的函数中。 promise 本身不能“重启”。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2018-02-17
      • 2019-05-27
      相关资源
      最近更新 更多