How to wait for an IPCRenderer callback

waiting for a reply – Fabio Melloni

In an Electron App, waiting for an IPCRenderer message callback could be useful to prevent managing empty content before that the main process sends it.

In your Renderer, you could call an ipcRenderer.send then immediately listen to a ipcMain.send reply, then you call the resolve method of this Promise.

const {ipcRenderer} = require('electron');

function getMainData(args) {
    return new Promise(resolve => {
        ipcRenderer.send('SEND_FROM_RENDERER', args);
        ipcRenderer.on('RECEIVE_FROM_MAIN', (event, result) => {
            resolve(result);
        });
     });
}

Then, in your Renderer script, you can call it like this:

getMainData("ping').then( res => {
    console.log(res) // "pong"
});

If this was useful to you, or if you have a better solution, please adds a comment below.