'Return not waiting for if condition
any one can help me.. I am developing a small project in Electron js. as a beginner I could not find any solution for this issue. I have search a lot similar problem discussed but I could not find it.
I want store data locally with Sqlite but when application open in first time in a new system, user should set database location. for that purpose I have write some code in main process and renderer.
here is code in Main process
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)
})
}
})
in render
dbConnection: function () {
ipcRenderer.invoke('read-user-data')
.then(dbPath => {
console.log('invoke is: ' + dbPath)
})
}
but the result always getting undefined. I guess problem with async function. but I could not find the right solution
can any one help me
Solution 1:[1]
This problem solved with sync method
here is the corrected code
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
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | midnight-coding |