用蓝鸟链接递归承诺 [英] chaining recursive promise with bluebird

查看:78
本文介绍了用蓝鸟链接递归承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有递归承诺doAsyncRecursive()的承诺链,如下所示:

I have a promise chain with a recursive promise doAsyncRecursive() in the middle like so:

doAsync().then(function() {
    return doAsyncRecursive();
}).then(function() {
    return doSomethingElseAsync();
}).then(function(result) {
    console.log(result);
}).catch(errorHandler);

doAsyncRecursive()必须做点什么如果它最初没有成功,那么我想在每5秒钟尝试一次,直到它完成。这是我的promise函数的样子:

doAsyncRecursive() has to do something and if it at first does not succeed, i then after want to try every 5 seconds until it does. This is what my promise function looks like:

function doAsyncRecursive() {
    return new Promise(function(resolve, reject) {
        //do async thing
        if (success) {
            resolve();
        } else {
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    doAsyncRecursive();
                }, 5000);
            });
        }
    });
}

但是当我执行时,链条在 doAsyncRecursive()在第二次尝试成功并且 resolve()被调用(如果第一次尝试尝试成功,则会继续) 。

But when I execute, the chain does not continue after doAsyncRecursive() is successful on the 2nd try and resolve() is called (it continues if the attempt is successful on the 1st try however).

我需要什么模式才能使这项工作?

What pattern do I need to make this work?

推荐答案

抓住失败,等待五秒钟,然后再试一次。

Catch the failure, wait five seconds, then try again.

function doAsyncRecursive() {
    return doAsyncThing().catch(function() {
        return Promise.delay(5000).then(doAsyncRecursive);
    });
}

这里 doAsyncThing 是在OP的代码中对应于 // do async thing 注释的函数,定义为返回一个promise。在原始代码中,使用 success 标志测试do async thing的成功或失败,但根据定义,异步例程不会提供这样的标志;他们通过回调或承诺提供结果。上面的代码假定 doAsyncThing 返回一个promise。它还假设失败,在不返回我想要的反应的意义上,由拒绝的承诺表示。如果将成功或失败定义为履行承诺的某个特定值,那么您要做

Here doAsyncThing is a function corresponding to the //do async thing comment in the OP's code, defined as returning a promise. In the original code, the success or failure of the "do async thing" is tested using a success flag, but by definition asynchronous routines do not deliver such a flag; they deliver their results either via a callback or a promise. The code above assumes that doAsyncThing returns a promise. It also assumes that "failure", in the sense of "does not return the response i want", is represented by that promise rejecting. If instead "success" or "failure" is to be defined as some particular value of a fulfilled promise, then you'd want to do

function doAsyncRecursive() {
    return doAsyncThing().then(function(success) {
        if (success) return success;
        else return Promise.delay(5000).then(doAsyncRecursive);
    });
}

这篇关于用蓝鸟链接递归承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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