什么是使用Promise的“超时间隔”的好模式

我正在写一些代码,每N毫秒轮询一个资源,这应该在M秒后超时。 我希望整个事情尽可能地使用蓝鸟的承诺。 到目前为止,我所提出的解决scheme使用节点间隔,可取消的蓝鸟许诺和蓝鸟的超时function。

我想知道是否有更好的方法来做蓝鸟和一般的承诺超时间隔? 主要是通过确保时间间隔停止在这一点,永远不会无限期地继续下去。

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 

我会做这样的事情 –

 function poll() { return Promise.resolve().then(function() { console.log('Polling...'); if (conditionA) { return Promise.resolve(); } else if (conditionB) { return Promise.reject("poll error"); } else { return Promise.delay(1000).then(poll); } }) .cancellable() } 

也要注意Promise构造函数的反模式

Rene Wooller提出了一个非常好的观点:

警告:不幸的是,像这样的JavaScriptrecursion将最终饱和调用堆栈,并导致内存不足的例外

即使没有例外,这也是浪费的空间,而例外的风险可能会导致投票延迟。

我认为这是非常重要的更喜欢setInterval:

 var myPromise = new Promise((resolve, reject) => { var id = window.setInterval(() => { try { if (conditionA) { window.clearInterval(id); resolve("conditionA"); } else if (conditionB) { throw new Error("conditionB!"); } } catch(e) { window.clearInterval(id); reject(e); } }, 1000); }); 

有几个npm软件包可以满足这个要求,其中我最喜欢promise-wait 。 这是38行,做这个工作。

 var myPromise = waitFor(() => { if(conditionA) return true; if(conditionB) throw new Error("conditionB!"); return false; });