Shiladitya Bose
Shiladitya Bose

Reputation: 1203

How to pass optional callback function to ipcRenderer.on() in ElectronJS

I'm trying to implement something as followed. In the renderer process, I have an async function foo() which takes an optional argument bar as a callback function reference.

After receiving success from the main process (not shown here) and getting a return object from the main process, it does something with the object and then calls the callback function that I passed as the argument.

Now, why it is needed is that I have two functions func1 and func2, the first one calls foo along with bar supplied. The second one doesn't.

How do I implement this?

import { ipcRenderer } from "electron";

// in renderer 

async function foo(/*optional function reference*/ bar) {
    ipcRenderer.send('message', {
        //options
    });

    ipcRenderer.on('success', (event, obj) => {
        //process obj
        bar();  //callback function passed as argument
    })
}

async function func1() {
    foo(bar)
}

async function func2() {
    foo() //no function passed
}


function bar() {
    console.log("hello world")
}

Upvotes: 0

Views: 1240

Answers (1)

Shiladitya Bose
Shiladitya Bose

Reputation: 1203

Found this link

ipcRenderer.on('success', (event, obj) => {
        //process obj
        if (bar) {
           bar();  //callback function passed as argument
        }
    })

Seems to do the trick.

Upvotes: -1

Related Questions