2

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.

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.