Electron:我不断从渲染器进程中的主进程获取未定义的值

问题描述 投票:0回答:1

我不断从渲染器进程的主进程中获取未定义的值。我正在使用 ipcRenderer.invoke 和 ipcMain.handle。

主要流程(直接截到这一段):

ipcMain.handle('process-message-to-gemini', async (event, chatMessage) => {
  const API_KEY = 'AIzaSyC30Qftd1JbdwZbMS_wbyoOhHtjza1pYOg'
  const genAI = new GoogleGenerativeAI(API_KEY)
  const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' })

  const prompt = chatMessage.message

  const result = await model.generateContent(prompt)
  const response = await result.response
  const text = response.text()
  console.log(text)
  return text
})

预载:

import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  processMessageToChatGPT: (chatMessages) => {
    ipcRenderer.invoke('process-message-to-chatgpt', chatMessages)
  },
  processMessageToGemini: (chatMessage) => {
    ipcRenderer.invoke('process-message-to-gemini', chatMessage)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}

渲染器流程(直接切到这一段):

try {
      const response = await window.api.processMessageToGemini(newMessage);
      console.log(response)
      setMessages([...newMessages, {
        message: response,
        sender: "Gemini",
        direction: "incoming"
      }])
    } catch (error){
      console.error('Error:', error.message);
    } finally {
      setTyping(false)
    }

我在渲染器进程中得到的响应是未定义的。我做错了什么?

我希望收到双子座的短信

electron
1个回答
0
投票

预加载.js

编辑 processMessageToGemini 以返回一个值。

 processMessageToGemini: async (chatMessage) => {
    const result = await ipcRenderer.invoke('process-message-to-gemini', chatMessage)
    return result;
 }
© www.soinside.com 2019 - 2024. All rights reserved.