0

I'm a JavaScript beginner and just finished reading "JavaScript The good parts". Now, I'm trying to understand and demystify closure and callbacks in JavaScript. Below is a piece of code which I assume should produce numbers from 1 through 10. However the code fails to compile (I'm using node btw).

var someAsyncFn = function() {};
for (var i = 0; i < 10; i++) {
    (function(j) {
        someAsycFn(function() {
            console.log(j);
        });
    })(i);
}

Here is the error log:

        someAsycFn(function() {
        ^
ReferenceError: someAsycFn is not defined
1
  • Please note that the error of the missing 'n' has been removed. However I'm unable to print the numbers from 1 through 10. Commented Feb 4, 2013 at 2:08

1 Answer 1

2

You've made a spelling error:

var someAsyncFn = function() {};
someAsycFn(function() {

Your call to the function omits the letter n.


The reason it doesn't work at all is that this is not real code. It is an example. someAsyncfn is not a real function. It does nothing. var someAsyncFn = function() {}; makes a function that does nothing. It's a placeholder to describe what would happen if there was a real asynchronous function.

Something like this would show the effect in a web browser (you'd need to use a different asynchronous function in node.js; I'm using jQuery to keep the code clean).

var someAsyncFn = function(successfn) {
    $.get(document.location, successfn); // make an AJAX request to the current URL, for demonstration purposes
                                         // successfn will be called when the request succeeds
};
for (var i = 0; i < 10; i++) {
    (function(j) {
        someAsyncFn(function() {
            console.log(j);
        });
    })(i);
}

This works because (a) the function containing console.log is now actually called and (b) because it is called asynchronously, when the $.get request is complete.

The whole point of this is that the code runs asynchronously, which means you won't get 0 to 9 in order; you'll get them in the order that the requests completed. For me, this was:

2
3
1
0
4
5
6
7
8
9

You will probably get a different result.

Sign up to request clarification or add additional context in comments.

1 Comment

@lonesomeday, have you got a working example of the code (jQuery or node.js) to explain your answer better?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.