Ben*_*aum 24
在我看来,这里的所有答案都非常复杂.Kos有正确的想法,但您可以通过编写更多惯用的承诺代码来缩短代码:
function retry(operation, delay) {
return operation().catch(function(reason) {
return Q.delay(delay).then(retry.bind(null, operation, delay * 2));
});
}
Run Code Online (Sandbox Code Playgroud)
并附有评论:
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));
});
}
Run Code Online (Sandbox Code Playgroud)
如果你想在一段时间后计时(让我们说10秒,你可以简单地做:
var promise = retry(operation, 1000).timeout(10000);
Run Code Online (Sandbox Code Playgroud)
该功能内置于Q版,无需重新发明:)