Issue
I am learning NodeJS, coming from other languages (C#, etc) and I find some of the syntax to be confusing.
For example this piece of code:
for(var index in files) {
console.log("-->"+index);
var task = (function(file) {
return function() {
fs.readFile(file, function(err, text) {
if (err) throw err;
countWordsInText(text);
checkIfComplete();
});
}
})(filesDir + '/' + files[index]);
tasks.push(task);
}
What is this? var task= (function(file){return function(){......}})(filesDir+.....);
There is a function that is calling a function and suddenly some parameters outside?
I am guessing it is defining a list of functions but what is the rule for this syntax?
Solution
It's called IIFE (Immediately Invoked Function Expression). Basically, you define a function
function (){}
and immediately execute it
(function(){})();
What the code you've posted is doing is, executing a function and storing the returned value in task
.
Answered By - Manish Gharat Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.