Return 不等待 if 条件

Return not waiting for if condition

任何人都可以帮助我..我正在用 Electron js 开发一个小项目。作为初学者,我找不到解决此问题的任何方法。我已经搜索了很多讨论过的类似问题,但我找不到。

我想用 Sqlite 在本地存储数据,但是当应用程序在新系统中第一次打开时,用户应该设置数据库位置。为此,我在主进程和渲染器中编写了一些代码。

这是主进程中的代码

ipcMain.handle('read-user-data', async (event, fileName) => {

    const checkPath = path.join(app.getPath('userData'), '\Local Storage/config.json')

    const dbPathExist = fs.readJsonSync(checkPath, { throws: false })

    if (dbPathExist === null) {
        dialog.showOpenDialog({ properties: ['openFile'] })
            .then(dgRresult => {
                if (!dgRresult.canceled) {

                    try {
                        fs.writeJson(checkPath, { dbPath: dgRresult.filePaths[0] })
                        FinaldbPath = dgRresult.filePaths[0]
                        return FinaldbPath

                    } catch (err) {
                        console.error("521: " + err)
                    }

                } else {
                    win.close()
                }
            })
            .catch((error) => {
                console.error("522: " + error)
            })
    } else {

        fs.readJson(checkPath)
            .then(packageObj => {
                FinaldbPath = packageObj.dbPath

                console.log(typeof (FinaldbPath))
                return FinaldbPath
            })
            .catch(err => {
                console.error(err)
            })
    }
})   

渲染中

dbConnection: function () {
    ipcRenderer.invoke('read-user-data')
        .then(dbPath => {
            console.log('invoke is: ' +  dbPath)
        })
}

但结果总是不确定。 我猜异步函数有问题。但我找不到合适的解决方案

谁能帮帮我

这个问题用同步方法解决了

这里是更正后的代码

ipcMain.handle('read-user-data', async (event, fileName) => {

    const checkPath = path.join(app.getPath('userData'), '\Local Storage/config.json')

    const dbPathExist = fs.readJsonSync(checkPath, { throws: false })

    if (dbPathExist === null) {
        selectedPath =  dialog.showOpenDialogSync({ properties: ['openFile'] })
   
        if (selectedPath) {

            try {
                fs.writeJson(checkPath, { dbPath: selectedPath[0] })
                FinaldbPath = selectedPath[0]
                return FinaldbPath

            } catch (err) {
                console.error("521: " + err)
            }


        } else {
            win.close()
        }
 
    } else {

        const packageObj = fs.readJsonSync(checkPath)
        FinaldbPath = packageObj.dbPath

        return FinaldbPath
    }
})