Reputation: 5823
In node let's say I have the following code:-
function readDirectory(callback){
fs.readdir('./', filterList);
}
function filterList(err,data){
//callback is undefined
if(err) callback(err);
callback();
}
readDirectory(function(){
console.log("Hi");
}
But the following works if I define function inside the readDirectory
itself because it's in the same scope:-
function readDirectory(callback){
fs.readdir('./', function(err,data){
if(err) callback(err);
callback();
});
}
readDirectory(function(){
console.log("Hi");
}
So my question is, is there a way to pass the scope of readDirectory
to the callback function that's defined outside?
Upvotes: 0
Views: 68
Reputation: 816462
So my question is, is there a way to pass the scope of readDirectory to the callback function that's defined outside?
No, JavaScript has lexical scope. However, you can make filterList
accept a callback:
function readDirectory(callback){
fs.readdir('./', filterList(callback));
}
function filterList(callback) {
return function(err,data){
if(err) callback(err);
callback();
};
}
Upvotes: 2