0

I am trying to call a async function every minute for 5 minutes before exiting the main function. Below is the print_data() function which I am calling in main() function.

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


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

main()

Very new to writing async function. What is the best way to call print_data function every minute for 5 minutes and print the output each minute? I tried something using setInterval and was not able to execute the function completely.

Any help would be good. Thank you in advance.

csvb
  • 365
  • 2
  • 6
  • 14

2 Answers2

0

Please check if the below code can be a solution.

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()
critrange
  • 5,652
  • 2
  • 16
  • 47
  • What if this function returns a promise and not console logs the data? `var print_data = async () => {console.log("Hello")}` I tried the above two suggestions with a function returning promise and was not able to change it based on promise calls? @yash – csvb Jul 14 '20 at 07:55
  • Previously I was seeing the "Hello" printed because of `console.log("Hello")`. If removed, I only see one "Hello" printing in the stdout. @yash – csvb Jul 14 '20 at 16:56
  • Got some answets from another stackoverflow question - https://stackoverflow.com/questions/52184291/async-await-with-setinterval. This is working :) Thank you for helping here. – csvb Jul 15 '20 at 10:21
0

This is one way to do it using setInterval and clearInterval. Read more about it here: https://nodejs.org/api/timers.html#timers_clearinterval_timeout

Using IIFE to prevent polluting of the global scope.

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

})();
Venkat Shukla
  • 168
  • 1
  • 8