开发者

Callback in Node.js

开发者 https://www.devze.com 2023-03-28 09:23 出处:网络
Today I am testing callback function in node.js My code is 开发者_如何转开发function callback_test(callback) {

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 ?


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);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消