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

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

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -