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

标签 javascript node.js asynchronous

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

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

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

最佳答案

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

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 实现。然而,如果你想包含像 bluebird 这样的东西,你可以找到更强大的工具,比如函数或整个模块的 promise 和 promise 超时。

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

我认为这是首选方法。 希望这有帮助

关于javascript - 如何设置在 node.js 中运行异步函数的时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587789/

相关文章:

javascript - jQuery 事件命名空间中所有事件的一个监听器?

javascript - 过滤前抛出异常?

javascript - 将 JS 函数转换为 jQuery

javascript - 单个 WordPress 页面上的单个 JavaScript 函数

javascript - javascript中do-while循环的用例?

javascript - 如何在发送响应 Node js (Sails) 之前设置 cookie

javascript - JS - 如何从不同的文件 Hook 成功和错误回调

mysql - NodeJS MySQL 转储

javascript - 如何在 npm 脚本中将 pug(jade) 渲染为 html?

javascript - 如何从 Google map JavaScript 地理编码器回调返回变量?