Skip to content

Instantly share code, notes, and snippets.

@averagesecurityguy
Created September 23, 2013 23:56
Show Gist options
  • Save averagesecurityguy/6678618 to your computer and use it in GitHub Desktop.
Save averagesecurityguy/6678618 to your computer and use it in GitHub Desktop.
Javascript callbacks
/*
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));
}
@alyawn
Copy link

alyawn commented Sep 24, 2013

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, the testExt(file) function is called once when the line is reached and the result of the call to testExt(file) is then "called" for each file in the array. Of course, if testExt(file) doesn't return a function object then you will get errors. Also, in the second example the file variable is not defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment