Print empty map JavaScript

I'm using a map to add values from iterating a text file. Inside the loop to read the txt file the map is not empty. But outside from the loop the map is returning empty.

function processTxt(inputFile) {

    var instream = fs.createReadStream(inputFile),
        outstream = new (require('stream'))(),
        rl = readline.createInterface(instream, outstream);

    var myMap  = new Map();


    rl.on('line', function (line) {
      var array = line.split(" ");

      if(line.startsWith("/")) {
        myMap.set(array[1], array[3];

      }

      //If I print the map here the map is not empty
      myMap.forEach((value, key) => {
           console.log(`${key} = ${value}`);
      }, myMap);

    });


    //The map outside the function here is returning empty.
    myMap.forEach((value, key) => {
        console.log(`${key} = ${value}`);
    }, myMap);


    return myMap;
}

2 answers

  • answered 2019-06-11 23:17 MattB

    You're printing out the map before it's been loaded. rl.on is an async function so it immediately continues to the next line (the myMap.forEach...).

  • answered 2019-06-11 23:18 Nate

    readline.on is an asynchronous function that sets up an event listener. The flow of your program is such that the readline.on() function call is put into the event loop and all your code that follows it happens first.

    Check out this fantastic video on understanding the event loop: https://www.youtube.com/watch?v=8aGhZQkoFbQ