I am new to Electron nodejs app. I make a call from html to main.js using ipcRenderer.on call. The code in main.js follows below, where i read an array of folders, fetch files from each folder and read contents from each file to process further. Now the problem is that the main function does not wait for the content read function to return the data.
ipcMain.on('worker', async (event, arg) => {
for (let x = 0; x < folders.length; x++) {
event.reply("dex-worker", dexFolders[x].path);
// Scan folders for files
fs.readdir(folders[x].path, (err, files) => {
// Process files
files.forEach(async (file) => {
event.reply("worker", file.toString()); // THIS WORKS
var fdata = await readData(files[x].path + path.sep + file); // DOES NOT WAIT for RETURN
console.log(fdata); // displays 'undefined'});
});
}
});
async function readData(fi) {
var _fdata = "";
fs.readFile(fi, 'utf8', function (err, data) {
if (err) {
console.log(err);
}
_fdata = data;
return (_fdata);
});
}
I read many post and docs regarding async/await and promise. But i do not understand whether they are together or alternatives. Please help.
You can use callback to get data properly.
ipcMain.on('worker', async (event, arg) => {
for (let x = 0; x < folders.length; x++) {
event.reply("dex-worker", dexFolders[x].path);
// Scan folders for files
fs.readdir(folders[x].path, (err, files) => {
// Process files
files.forEach(async (file) => {
event.reply("worker", file.toString()); // THIS WORKS
readData(files[x].path + path.sep + file, (err, data) => {
if (err) {
console.log(err);
}
console.log(data);
});
});
})
}
});
function readData(fi, callback) {
fs.readFile(fi, 'utf8', callback);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.