Your message handler is synchronous, therefore the getFile
call is fired but the handler does not wait until it finishes execution, and sends the current value of contents
(undefined because at this point getFile
has not yet changed it).
You need to make the handler async and await the getFile
call.
ipcMain.on('asynchronous-message', async (event, arg) => {
await getFile()
mainWindow.webContents.send('asynchronous-message',contents)
mainWindow.openDevTools();
})
Or better yet, get rid of the global variable by handling what getFile
does directly in the handler (it's also better to use non-blocking fs
functions):
ipcMain.on('asynchronous-message', async (event, arg) => {
const {filePaths} = await dialog.showOpenDialog({properties:['openFile']});
const contents = await fs.promises.readFile(filePaths[0], 'utf-8');
mainWindow.webContents.send('asynchronous-message', contents);
mainWindow.openDevTools();
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…