如何设置在node.js中运行asynchronous函数的时间限制?

有一个asynchronous函数fun(param, callback)像这样:

 fun(param, function(err){ if(err) console.log(err); doSomething(); }); 

如何设置运行此function的时间限制?
例如,我设定的时间限制等于10秒。
如果在10秒内完成,没有错误。
如果运行超过10秒,则终止并显示错误。

承诺是这种types的行为,你可以有这样的理想:

 new Promise(function(resolve, reject){ asyncFn(param, function(err, result){ if(error){ return reject(error); } return resolve(result) }); setTimeout(function(){reject('timeout')},10000) }).then(doSomething); 

这是使用基本的ES6 Promise实现。 然而,如果你想包括像蓝鸟这样的东西,你可以find更多的function,如function或整个模块的promisification和承诺超时。

http://bluebirdjs.com/docs/api/timeout.html

这在我看来是首选的方法。 希望这可以帮助

做到这一点的最简单的方法是捕捉承诺的function。

 var Promise = require("bluebird"); var elt = new Promise((resolve, reject) => { fun(param, (err) => { if (err) reject(err); doSomething(); resolve(); }); elt.timeout(1000).then(() => console.log('done')) .catch(Promise.TimeoutError, (e) => console.log("timed out")) 

我做了一个模块“智能定时器”

 var timer = require('intelli-timer'); timer.countdown(10000, function(timerCallback){ // time limit is 10 second do_something_async(err, function(){ timerCallback(); // timerCallback() after finish }); }, function(err){ if(err) console.log(err); // err is null when the task is completed in time else console.log('success'); });