如何设置在node.js中运行异步函数的时间限制? [英] How to set a time limit to run asynchronous function in node.js?

查看:114
本文介绍了如何设置在node.js中运行异步函数的时间限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何设置运行此功能的时间限制?

例如,我设置时间限制等于10秒。

如果它在10秒内完成,则没有错误。

如果它运行超过10秒,则终止它并显示错误。

解决方案

承诺非常适合您可以拥有的行为:

  new Promise(function(resolve,reject){
asyncFn(param,function(err,result){
if(error){
返回拒绝(错误);
}
返回解析(结果)
});

setTimeout(function(){reject('timeout')},10000 )
})。then(doSomething);

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



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



<在我看来,这是首选方法。
希望这有助于


There is a asynchronous function fun(param, callback) like this:

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

How do I set a time limit to run this function?
For example, I set time limit equals to 10 secs.
If it finish in 10 seconds, there is no error.
If it run exceed 10 seconds, terminate it and show error.

解决方案

Promises are ideal for this kind of behavior you could have something like:

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);

this is using the basic ES6 Promise implementation. however if you want to include something like bluebird you can find more powerful tools like promisification of functions or entire modules and promise timeouts.

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

this in my opinion would be the preferred approach. Hope this helps

这篇关于如何设置在node.js中运行异步函数的时间限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆