0

I'm trying to read in from a text file and store them in a array of my Lease class. If I console.log() from inside the my final loop it will print the loop in its current state for each iterration. But if I move the console.log outside the loop it prints an empty array.

working as expected

const readline = require('readline'),
  fs = require('fs');

function Lease(renter, unit) {
  this.unit = unit;
  this.renter = renter;
}

var list = [];

var rl = readline.createInterface({
  input: fs.createReadStream('input.txt'),
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line) {
  var values = line.split(' - ');
  list.push(new Lease(values[0], values[1]));
  console.log(list);
});

printing empty array

const readline = require('readline'),
  fs = require('fs');

function Lease(renter, unit) {
  this.unit = unit;
  this.renter = renter;
}

var list = [];

var rl = readline.createInterface({
  input: fs.createReadStream('input.txt'),
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line) {
  var values = line.split(' - ');
  list.push(new Lease(values[0], values[1]));
});

console.log(list);
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188

1 Answers1

2

In the first version, the console.log() is in the callback function, it will be executed when the callback function is invoked.

However, in the second version, the console.log() will be called before the callback function of on.('line' executed...

The callback function is Async, it won't be executed until current stack is empty...

zangw
  • 43,869
  • 19
  • 177
  • 214