1

Today I am testing callback function in node.js

My code is

function callback_test(callback) {
    for(i=0;i<=10;i++){
        callback(i);
    }
}

callback_test(function(result) {
    console.log(result);
    callback_test(function(result2){
        console.log(result2);
    });

});

The output is

0 0 1 2 3 4 5 6 7 8 9 10

The result should be

0

0 to 9 and

1

0 to 9 again.

However, first callback is not working all loop. it's only working first loop. Why ?

1 Answer 1

5

You need to declare i in the function, otherwise you get a global variable (which the nested invocation shares and thus it gets counted up to ten only once):

function callback_test(callback) {
  for(var i=0;i<=10;i++){
      callback(i);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.