【问题标题】:How to set a time limit to run asynchronous function in node.js?node.js 中如何设置运行异步函数的时间限制?
【发布时间】:2016-08-03 22:08:52
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript node.js asynchronous


【解决方案1】:

Promise 非常适合这种行为,你可以有类似的东西:

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 之类的东西,您可以找到更强大的工具,例如功能或整个模块的承诺和承诺超时。

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

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

【讨论】:

    【解决方案2】:

    我已经制作了一个模块'intelli-timer'

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

    【讨论】:

      【解决方案3】:

      最简单的方法是在 Promise 中捕获函数。

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

      【讨论】:

        猜你喜欢
        • 2020-10-07
        • 2018-01-16
        • 2021-07-26
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        相关资源
        最近更新 更多