In the next example I don't have access to variable "locals" inside the functions "fetcher", "parser" and "saveToDb".
var parser = require('parser.js');
var fetcher = require('fetcher.js');
var saveToDb = require('models/model.js');
var async = require('async');
function task() {
var locals = [] //<-- declared here
async.series([
fetcher, //<-- can not access "locals"
parser, //<-- can not access "locals"
saveToDb //<-- can not access "locals"
],
function (err) {
if (err) return callback(err);
callback(null);
});
}
In the next example "local"s is accessible. I just copyed the functions declarations from the requested modules, and pasted them straight inside "async.series".
var async = require('async');
function task() {
var locals = [] //<-- declared here
async.series([
function(callback) {// <-- can access "locals"},
function(callback) {// <-- can access "locals"},
function(callback) {// <-- can access "locals"}
],
function (err) {
if (err) return callback(err);
callback(null);
});
}
While this works - I do want to keep my code modular. How can I fix that ? Or - what I forgot here about the fundamentals of JavaScript ?
Thanks.
locals
variable) defined elsewhere. Making something modular usually takes more than just spreading things around files, it's also about making relationships between different parts of your code explicit, for example by passing all data a function needs as arguments. – Mae