Search code examples
node.jsnode-red

Repeat a function and wait for x seconds after it is complete


I am developing my own node-red node that is going to make use of minimodem. So I have a function executesend that is calling a child process. It looks something like this:

       function executesend(){
            
            exec('echo ' + msg.payload + ' | minimodem --tx ' + options + ' ' + baudmode, (error, stdout, stderr) => {

                if (error) {
                    console.log(`error: ${error.message}`);
                    return;
                }
                if (stderr) {
                    console.log(`stderr: ${stderr}`);
                    return;
                }
                console.log(`stdout: ${stdout}`);
            });
    };

Now I planned to implement a repeat function, to repeat sending the same message several times!

        if (repeat){
            if (typeof(repeatdelay) != 'undefined' && typeof(repeatxtimes) !="undefined"){
                for (i = 0; i <= parseInt(repeatxtimestoint); i++){
                    
                    
                        executesend()
                        await new Promise(r => setTimeout(r, repeatdelaytoint));
                        
                  
                }
            }
            else{
                console.error('Repeat settings not configured!')
                node.error('Repeat settings not configured!')

            }
        }
        executesend() 

But I noticed that all of the repeats happened instant after I send a msg. I believe there is an easy solution for this, could someone help?


Solution

  • for your same code. what you could do is convert execution send & return promise from it (with async or promise).

    function executesend(){
      return new Promise((res, rej) => {
        // your code
        res("when execution gets complete")
      })
    }
    
    or
    
    async function executesend(){
      return "when execution gets complete"
    };
    

    and in your another for loop code. // edit new start make sure you'll declare your function with async if await is being used inside. error is from syntactical error. as without async usage of await is not allowed.

    async function yourFunctionWithForLoop(){
      for (i = 0; i <= parseInt(repeatxtimestoint); i++){
        await executesend()
        await new Promise(r => setTimeout(r, repeatdelaytoint));
      }
    }
    

    // edit new end

    currently in your code settimeout (for loop one) is getting called before exec execution & getting resolved after whatever time it's given.

    i hope it helps