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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -