Created
September 23, 2013 23:56
-
-
Save averagesecurityguy/6678618 to your computer and use it in GitHub Desktop.
Javascript callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Why does the first function work properly but the second does not? The second one fails | |
because the file variable does not get properly passed to testExt. | |
*/ | |
/* Example 1 */ | |
function listFiles(err, files) { | |
if (err) throw err; | |
files.forEach(function (file) {testExt(file);}); | |
} | |
/* Example 2 */ | |
function listFiles(err, files) { | |
if (err) throw err; | |
files.forEach(testExt(file)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well,
forEach
expects a function callback. In the first example, you correctly pass a function object (or pointer if you prefer). In the second example, thetestExt(file)
function is called once when the line is reached and the result of the call totestExt(file)
is then "called" for each file in the array. Of course, iftestExt(file)
doesn't return a function object then you will get errors. Also, in the second example thefile
variable is not defined.