javascript - Nodejs array not working as expected -


i'm trying read in text file , store them in array of lease class. if console.log() inside final loop print loop in current state each iterration. if move console.log outside loop prints empty array.

working 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); 

in first version, console.log() in callback function, executed when callback function invoked.

however, in second version, console.log() called before callback function of on.('line' executed...

the callback function async, won't executed until current stack empty...


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -