“超时间隔”的良好模式我正在编写一些代码,每N毫秒轮询一个资源,这应该在M秒后超时。我希望整个事情都是尽可能使用蓝鸟的承诺。到目前为止,我提出的解决方案使用节点间隔,可取消蓝鸟许诺和蓝鸟超时功能。使用Promises
我想知道是否有更好的方法来做蓝鸟和一般的承诺超时间隔?主要是通过确保间隔停止在这一点,永远不会无限期地继续下去。
var Promise = require('bluebird');
function poll() {
var interval;
return new Promise(function(resolve, reject) {
// This interval never resolves. Actual implementation could resolve.
interval = setInterval(function() {
console.log('Polling...')
}, 1000).unref();
})
.cancellable()
.catch(function(e) {
console.log('poll error:', e.name);
clearInterval(interval);
// Bubble up error
throw e;
});
}
function pollOrTimeout() {
return poll()
.then(function() {
return Promise.resolve('finished');
})
.timeout(5000)
.catch(Promise.TimeoutError, function(e) {
return Promise.resolve('timed out');
})
.catch(function(e) {
console.log('Got some other error');
throw e;
});
}
return pollOrTimeout()
.then(function(result) {
console.log('Result:', result);
});
输出:
Polling...
Polling...
Polling...
Polling...
poll error: TimeoutError
Result: timed out
不错。你将如何完成这个时间间隔?看起来像是抛出错误的唯一出路。我知道Promise构造函数是一种反模式,但在这种情况下它似乎很适合(与事件+ Promises相同,但这是另一个主题)。 – Chris911
好吧,现在我明白你的问题。检查我的编辑。 – vinayr
是的,这是有效的。谢谢并接受答案。 – Chris911