0

I iterate over the repository and parse JSON files there. I populate batch array with the data in order to use it later for batch insert using pg.

This is how I populate batch array

const batch = [];
dir.readFiles('../resources/data/', { match: /\.json$/ }, (err, content, next) => {
    if (err) throw err;

    const jsn = JSON.parse(content);
    const generatorName = jsn.name;
    const generatorParts = jsn.name_parts;

    Object.entries(generatorParts).forEach(([key, value]) => {
        const pr_sp = value.precede_space;
        const ordr = value.order;
        const nm_prts = value.parts;

        nm_prts.forEach(item => {
            batch.push([generatorName, key, item, ordr, pr_sp]);
        });

    });

    next();
});
console.log(batch);

But console.log shows that the batch is empty. What is the problem?

lapots
  • 12,553
  • 32
  • 121
  • 242
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str May 25 '18 at 07:40
  • 2
    Console.log is executed way before the dir.readFiles callback. – Martin May 25 '18 at 07:42
  • @Martin hm...so I cannot display `batch` outside the callback? – lapots May 25 '18 at 08:39
  • 1
    .readFileSync() is synchronous as opposed to .readFile() that is asynchronous... console.log(batch) will be run before dir.readFile is finished so empty batch array will still be empty. – Todd May 25 '18 at 11:53
  • @Todd I see. So in this case basically every action I have to run inside the callbacks? `read files`, `connect to db` everything inside callbacks? – lapots May 25 '18 at 13:23
  • Well I guess there are two options, look into asyn concepts for js or a quick fix might be to use `var content = dir.readFileSync(...);` at the start of your code. This will work in the syncronous way you are expecting it too. – Todd May 25 '18 at 20:54

0 Answers0