I’m trying to learn javascript to work with node.js and obviously don’t quite get closures.
I’m try to read a file, line by line, parse the line and put the result into an array and return the array. Here’s what I have (doesn’t quite work):
var fs = require('fs'), Lazy = require('lazy');
function parseMyFile (filename) {
var myArray= [];
var lazy = new Lazy (fs.createReadStream(filename));
lazy
.lines
.map(function(line){
var parts = line.toString().split('|');
var item = {
bucket: parts[1],
uri: parts[2].substring(2),
token: parts[0],
fileDate: parts[3]
};
myArray.push (item);
});
console.log(myArray); // empty
return myArray;
};
var myItems = parseMyFile ('Tokens.csv');
I’m sure this has something to do with closures, just not quite getting it. Any help would be appreciated.
Thanks!
It’s a lazy list. It’s a wrapper around asynchronous behavior. You’re trying to examine the list before it’s been filled in, so of course it doesn’t work.
The problem has nothing to do with closures. It’s all about asynchronous behavior.
I don’t see anything in that lazy list code that allows a generic “when finished” callback.