【问题标题】:Call a async function every minute for 5 minutes in nodejs在nodejs中每分钟调用一个异步函数5分钟
【发布时间】:2020-11-02 11:04:51
【问题描述】:

我试图在退出主函数之前每分钟调用一个异步函数 5 分钟。下面是我在main() 函数中调用的print_data() 函数。

var print_data = async () => {
    console.log("Hello")
}


async function main() {
    process.stderr.write("--Start--")
    var data = await print_data()
    console.log(data)
}

main()

编写异步函数非常新。每分钟调用print_data函数5分钟并每分钟打印输出的最佳方法是什么?我尝试使用 setInterval 并无法完全执行该功能。

任何帮助都会很好。提前谢谢你。

【问题讨论】:

    标签: node.js async-await setinterval


    【解决方案1】:

    这是使用 setInterval 和 clearInterval 的一种方法。在此处阅读更多信息:https://nodejs.org/api/timers.html#timers_clearinterval_timeout

    使用IIFE 防止污染全局范围。

    (function (){
        let counter = 0;  //counter to keep track of number of times the setInterval Cb is called
        let data; // to store reference of Timeout object as returned by setInterval, this is used in clearInterval 
    
        const print_data = async () => {
            console.log("Hello")
            counter++;
            if (counter == '5') {
                clearInterval(data);
            }
        }
    
    
        async function main() {
            process.stderr.write("--Start--")
            data = setInterval(print_data, 1000*60); //60 seconds
        }
    
        main();
    
    })();
    

    【讨论】:

      【解决方案2】:

      请检查以下代码是否可以解决。

      var print_data = async () => {
          console.log("Hello")
          return "Hello";
      }
      
      var call_print_data = () => new Promise((resolve, reject) => {
          var count = 0;
          var interval = setInterval(async () => {
              var res = await print_data();
              count += 1;
      
              if (count === 5) { // if it has been run 5 times, we resolve the promise
                  clearInterval(interval);
                  resolve(res); // result of promise
              }
          }, 1000 * 60); // 1 min interval
      });
      
      async function main() {
          process.stderr.write("--Start--")
          var data = await call_print_data(); // The main function will wait 5 minutes here
          console.log(data)
      }
      
      main()
      

      【讨论】:

      • 如果这个函数返回一个promise而不是控制台记录数据怎么办? var print_data = async () => {console.log("Hello")} 我用一个返回promise的函数尝试了上述两个建议,但无法根据promise调用来改变它? @yash
      • 以前我看到因为console.log("Hello") 而打印了“Hello”。如果删除,我只会在标准输出中看到一个“Hello”打印。 @yash
      • 从另一个 stackoverflow 问题中得到了一些答案 - stackoverflow.com/questions/52184291/…。这是有效的 :) 感谢您在这里提供帮助。
      猜你喜欢
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2021-09-13
      • 2010-11-16
      • 2017-11-15
      • 2015-07-31
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多