Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Electron - Main process not wating for the showOpendialog to return file content

I have the following communication going on

//main process
ipcMain.on('asynchronous-message', (event, arg) => {
    getFile()
    mainWindow.webContents.send('asynchronous-message',contents)
    mainWindow.openDevTools();
})
async function getFile(){
  const {filePaths} = await dialog.showOpenDialog({properties:['openFile']});
  contents =  fs.readFileSync(filePaths[0],'utf-8')

}
//renderer process
function openFS(){
    ipc.send('asynchronous-message', 'ping')
    ipc.on('asynchronous-message',(event,arg)=>{
        console.log(arg)
    })
}

in the main process i have the getFile function that is fetching a files content but the ipc.Main doesn't wait for it it immediately returns undefined to the renderer process and thats what it prints on the dev tools
I know this for certain because if i remove the show open dialog and hard code the path to the file i wanna fetch , it successfully prints the content of the file in the dev tools because it doesnt need to spend the time on the file system

question from:https://stackoverflow.com/questions/65869144/electron-main-process-not-wating-for-the-showopendialog-to-return-file-content

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...