0

I'm trying to get my program to wait for an array of files to be read in before it continues execution.

Here's the code:

electron.js

ipcMain.on("toMain", (event, args) => {
  // TODO intigrate into JSON
  let files = [
    "1.txt",
    "2.txt",
    "3.txt",
    "4.txt",
    "5.txt",
    "6.txt",
    "7.txt",
    "8.txt"
  ];
  for (var file of files) {
    fs.readFile(path.join(__dirname, "/resources/"+file), "utf8", function(err, data) {
      win.webContents.send("fromMain", [err, data]);
    });
  }
});

preload.js

const {
contextBridge,
ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
    send: (channel, data) => {
        // whitelist channels
        let validChannels = ["toMain"];
        if (validChannels.includes(channel)) {
            ipcRenderer.send(channel, data);
        }
    },
    receive: (channel, func) => {
        let validChannels = ["fromMain"];
        if (validChannels.includes(channel)) {
            // Deliberately strip event as it includes `sender` 
            ipcRenderer.on(channel, (event, ...args) => func(...args));
        }
    }
}
);

index.js

// Reads all datafiles from src/resources
var data_files = [];
var data_errors = [];
window.api.receive("fromMain", (data) => {
    data_files.push(data[1]);
    data_errors.push(data[0]);
});
window.api.send("toMain", "some data");

I want an intelligent way of waiting for all the files to load through to my index.js array data_files before I continue with processing them. Any help is greatly appreciated!

Sean J
  • 31
  • 3

0 Answers0