Passing callbacks to the main process

When you are exposing a method to renderer process through the remote object, you can use callbacks in your functions to accept some values from the renderer process. In that way, a two-way communication between the processes is possible using the remote module. The exported method can accept the callback from the renderer process so that you can send processed result back to the main process. However, I recommend that you avoid using callbacks when working with remote module. There are the couple of reasons to avoid the callbacks. Before checking this reason, let’s check how this will work in Electron:

// In main process
const fs = require('fs');

export function readConfigurationAsync(callback) {
fs.readFile('./config.json', (content) => {
if(!content)
throw Error('Could not read file');
if(callback)
callback(JSON.parse(content));
});
}

// In renderer process
const { readConfigurationAsync } = require('electron').remote;
const config = readConfigurationAsync(cfg => {
console.log(`Configuration version is - ${cfg.version}`)
});

This is the same example that we discussed before, but changed to callbacks. You should be careful when using this; better avoid this always for the following reasons:

  • It’s very easy to get a deadlock with the callback on remote module inside the renderer process.
  • Callbacks passed to the main process will persist until the main process garbage collect them. Because of this, memory leaks can happen very easily.

If you are using it, always ensure that you clean up any references that you have passed through the callback to the main process upon completing the task.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.186.248