失败后重新启动承诺 [英] Restart a promise after fail

查看:71
本文介绍了失败后重新启动承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您需要将其包装在一个可以再次调用的函数中.promise 本身不能重启".

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)

这篇关于失败后重新启动承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆