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

Lar*_* Lu 7 javascript asynchronous node.js

有一个fun(param, callback)像这样的异步函数:

fun(param, function(err){
    if(err) console.log(err);
    doSomething();
});
Run Code Online (Sandbox Code Playgroud)

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

Day*_*eon 8

承诺是这种行为的理想选择,你可以拥有类似的东西:

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);
Run Code Online (Sandbox Code Playgroud)

这是使用基本的ES6 Promise实现.但是如果你想要包含像bluebird这样的东西,你可以找到更强大的工具,比如函数或整个模块的promisification和承诺超时.

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

我认为这是首选方法.希望这可以帮助