Search code examples
javascriptfunctionchild-process

Re-launch the same function when a child-process is closed


I'm working with a js class and I want that when the child_process this.youtube is closed, the function MainFunction() restarts again;

I know that, if you're inside of other functions, you can invoke this function with this.MainFunction(), so I tried the same putting it into the same function but I get the eror this.MainFunction() is not a function

Here's my code

const childprocess = require('child_process')
class Something {
    constructor(){

    }
    async MainFunction(){
        this.youtube=childprocess.spawn('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',["https://www.youtube.com/"]);
        this.youtube.on('close',function(){
            this.MainFunction()
        })
    }
}
module.exports = Something

Solution

  • It's because of the context which this inside function refers to. If you want it to refer to the Something class, then change the callback to arrow function:

    this.youtube.on('close',() => {
        this.MainFunction()
    })
    

    More on how this works can be found in this great post.