dimanche 22 mars 2015

NodeJS: function vs. anonymous function


Working on the stream-adventure NodeJS tutorial, but am struggling with the duplexer redux exercise.


This is what I've tried to use, but it doesn't work:



var duplexer = require('duplexer2');
var through = require('through2').obj;

module.exports = function (counter) {
var counts = {};
var input = through(write, end);
return duplexer(input, counter);

var write = function (row, _, next) {
counts[row.country] = (counts[row.country] || 0) + 1;
next();
}

var end = function (done) {
counter.setCounts(counts);
done();
}
};


This is the proposed solution, which works:



var duplexer = require('duplexer2');
var through = require('through2').obj;

module.exports = function (counter) {
var counts = {};
var input = through(write, end);
return duplexer(input, counter);

function write (row, _, next) {
counts[row.country] = (counts[row.country] || 0) + 1;
next();
}

function end (done) {
counter.setCounts(counts);
done();
}
};


Can someone help me understand the difference between using the anonymous function saved into a variable versus just naming a function?





Aucun commentaire:

Enregistrer un commentaire