0

So I'm building a command handler for an application and I'm wanting to build a dictionary from files that have the right modules. The dictionary is being set properly inside of the fs.readdir, but things are happening out of order for me and I can't figure out if its a context or a synchronous problem I'm not seeing.

        const dict = new Map();
        fs.readdir(filePath, (err, files) => {
            if (err) console.log(err);
            console.log(files);
            let jsfile = files.filter(f => f.split(".").pop() === "js");
            if (jsfile.length <= 0) {
                console.log("didn't see any commands.");
                return;
            }
                jsfile.forEach((f) => {
                    console.log(f);
                    let props = require(`${filePath}/${f}`);
                    try {
                        if(props.help.name)
                            dict.set(props.help.name, props);
                        console.log(`${f} was loaded.`);
                    }
                    catch (e) {

                    }
                });

            let run = dict.get('kata1');
            run.run();
            console.log(dict);
        });
        console.log(dict + "2");

for some reason console.log(dict+ "2"); populating first, then the rest of the logs in fs.readdir run. I've tried putting the read in a function and calling that function first, but I can't seem to access dict outside of the fs.readdir.

Slamerz
  • 21
  • 2
  • I've marked as duplicate because `fs.readdir` is async and that question provide the answer how to make it work. – jcubic Feb 17 '19 at 16:06

1 Answers1

0

like you mentioned it's a synchronous problem fs.readdir is async function.

the callback (err, files) => will call after all the sync function in the eventloop,

this -> console.log(dict + "2"); is a sync function.

read this:

hong4rc
  • 3,999
  • 4
  • 21
  • 40
Shay Moshe
  • 482
  • 4
  • 16