invoke a callback function after multiple ipcRenderer events in electronJS

382 views Asked by At

I want to invoke a callback function after two(multiple) ipcRenderer.on() fires. I tired this...

(async () => {
  await ipcRenderer.on('all-items-data-fetched', (event, data) => {
    itemData = data;    
  });  
  await ipcRenderer.on('all-groups-data-fetched', (event, data) => {
    data.forEach((el) => {
      groupObj[el.id] = el.name;
    
      const option = document.createElement('option');
      option.value = el.id;
      option.textContent = el.name;
      underGroup.appendChild(option);
    });
  });
})()
.then(() => { console.log(itemData);
  dataTable.clear().draw();

  itemData.forEach((el) => {  
    itemNames.push(el.name);
    el.groupId = groupObj[el.groupId];
    dataTable.row.add(el).draw();
  });

  table.querySelectorAll('button').forEach((el) => {
    el.addEventListener('click', tableActions);
  });
});

But not working, I want that first both IPC events ipcRenderer.on('all-items-data-fetched', (event, data) => {...} and ipcRenderer.on('all-groups-data-fetched', (event, data) => {...} should fire then a callback function should invoke. How can I do this?

1

There are 1 answers

0
Abhishek Sharma On

You can use promises.

const listener1 = Promise.resolve(ipcRenderer.on('all-items-data-fetched', (event, data) => {...})
const listener2 = Promise.resolve(ipcRenderer.on('all-groups-data-fetched', (event, data) => {...})

Promise.all([listener1, listener2])
                .then((values) => callback_function)
//values will be an array with value[0] and value[1] corresponding responses of listener1 and 2