「超時間隔」的良好模式我正在編寫一些代碼,每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