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);
}
}
精彩评论