我创建了以下程序来尝试帮助我理解 node.js 中的异步调用/回调,但最终却遇到了更多问题。
var z = 0
// define our function with the callback argument
function some_function(arg1, arg2, callback) {
// this generates a random number between
// arg1 and arg2
var my_number = Math.ceil(Math.random() *
(arg1 - arg2) + arg2);
// then we're done, so we'll call the callback and
// pass our result
callback(my_number);
}
// call the function - callback 1
some_function(5, 15, function(num) {
// this anonymous function will run when the
// callback is called
z = 1;
console.log("callback 1 called! " + num + " z= " + z);
});
// call the function - callback 2
some_function(20, 25, function(num) {
// this anonymous function will run when the
// callback is called
var x=3000;
z = 2;
setTimeout(function() {
console.log("callback 2 called! " + num + "-> but waited " + x + " z= " + z);
}
,x);
});
// call the function - callback 3
some_function(30, 35, function(num) {
// this anonymous function will run when the
// callback is called
var x=5000;
z = 3;
setTimeout(console.log("callback 3 called! " + num + "-> but waited " + x + " z= " + z), x);
});
//callback function for callback 4
function callback_function(my_num) {
z = 4;
console.log("callback 4 called! " + "-> but waited " + " z= " + z);
}
// call the function - callback 4
some_function(40, 45, function(num) {
// this anonymous function will run when the
// callback is called
var x=6000;
setTimeout(callback_function, x);
});
这是我得到的输出:
node callback_test.js
callback 1 called! 13 z= 1
callback 3 called! 35-> but waited 5000 z= 3
callback 4 called! -> but waited z= 4
callback 2 called! 25-> but waited 3000 z= 4
我的问题是:
据我了解,callback-3在立即执行
console.log
语句setTimeout
,而不是callback-2仅在setTimeout
完成时执行它 - 这是正确的吗?为了帮助我理解,为什么会这样?在callback-4
setTimeout
中,我为语句创建了另一个回调函数。该函数 (callback_function
) 有一个参数my_num
。如果我按照上面显示的方式运行它,它就会充当回调,但是当我像这样运行它时,setTimeout(callback_function(num), x);
它会立即执行它 - 为什么会发生这种情况?这与问题 2 有关。从
setTimeout(callback_function, x);
in callback-4中,我如何将参数传递给在 ?callback_function
中定义的类似参数function callback_function(my_num) {...
?