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' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -