承诺:重复操作直到成功? [英] Promises: Repeat operation until it succeeds?

查看:141
本文介绍了承诺:重复操作直到成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重复执行一个操作,每次操作之间的超时时间增加,直到成功或经过一定的时间。如何用Q中的promises构建它?

I want to perform an operation repeatedly, with an increasing timeout between each operation, until it succeeds or a certain amount of time elapses. How do I structure this with promises in Q?

推荐答案

我认为这里的所有答案都非常复杂。 Kos有正确的想法,但您可以通过编写更多惯用的承诺代码来缩短代码:

All the answers here are really complicated in my opinion. Kos has the right idea but you can shorten the code by writing more idiomatic promise code:

function retry(operation, delay) {
    return operation().catch(function(reason) {
        return Q.delay(delay).then(retry.bind(null, operation, delay * 2));
    });
}

并附有评论:

function retry(operation, delay) {
    return operation(). // run the operation
        catch(function(reason) { // if it fails
            return Q.delay(delay). // delay 
               // retry with more time
               then(retry.bind(null, operation, delay * 2)); 
        });
}

如果你想在一段时间后计时(让我们说10秒钟) ,你可以简单地做:

If you want to time it out after a certain time (let's say 10 seconds , you can simply do:

var promise = retry(operation, 1000).timeout(10000);

该功能内置于Q中,无需重新发明它:)

That functionality is built right into Q, no need to reinvent it :)

这篇关于承诺:重复操作直到成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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