【问题标题】:How can I call an ipcMain command from another ipcMain command?如何从另一个 ipcMain 命令调用 ipcMain 命令?
【发布时间】:2021-10-01 22:55:34
【问题描述】:

不幸的是,我是电子新手,为了保持干燥,我需要从 makeFolder 内部启动 loadFoldersloadFolders 将触发 ipcRenderer 加载我更新的文件夹名称的事件

所有在线示例都显示从 ipcMain 向 ipcRenderer 发送消息,但从不从一个后端函数发送到另一个,这甚至可能吗?

ipcMain.on('loadFolders', (e, args) => {
  // ...
  // does some stuff to read folder names from the file system
  // ...
  // sends folder list to the view
  mainWindow.webContents.send('folderItems', items)
})

ipcMain.on('makeFolder', (e, args) => {
  return new Promise((resolve, reject) => {
    try {
      // ...
      // creates a folder from args
      // ** need to call the loadFolders method here in order to read
      // updated list from the filesystem **
    } catch (err) {
      reject(err)
    }
  })
})

【问题讨论】:

  • loadFolders变成一个函数(而不是使用ipcMain),然后从makeFolder中调用它

标签: node.js electron


【解决方案1】:

正如其他人指出的那样,我不确定这是您应该做的事情。 话虽如此,你绝对可以! 你可以从你的主进程中发出一个事件,也可以在你的主进程中捕获它。

例如:在您的主进程中:

ipcMain.on('doSomething', ()=>{console.log('I did something!')});
ipcMain.emit('doSomething');

这将输出“我做了某事!”在您的控制台上。

【讨论】:

    【解决方案2】:

    在电子中,您只有一个主进程(如服务器)和多个渲染器进程(如浏览器中的选项卡)。

    IPC 代表进程间通信。但是主进程不需要IPC。例如,您可以使用常规函数调用。

    但是,如果您需要从主进程(反之亦然)或渲染器进程之间“对话”渲染器进程,请分别使用 ipcMain() 和 ipcRender()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 2022-01-24
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多