[英]Function not called asynchronously if I pass in an argument
I am trying to play around with callback functions. 我正在尝试使用回调函数。 I wanted to make my callback async and from what I understand, one of the ways is to call the
setTimeout
function to make my synchronous function, async. 我想让我的回调异步,根据我的理解,其中一种方法是调用
setTimeout
函数来生成我的同步函数async。 This works well, unless I try to pass an argument to my callback in setTimeout
: 除非我尝试在
setTimeout
中将参数传递给我的回调,否则这很有效:
var callback_function = function (funcArg) {
console.log("From Main Function");
setTimeout(funcArg, 10); // WATCH THIS LINE
console.log("From Main Function 2");
};
callback_function(function (arg) {
console.log("From Callback");
console.log(arg);
});
console.log("This should run before callback");
Output: 输出:
From Main Function 从主要功能
From Main Function 2 从主要功能2
This should run before callback 这应该在回调之前运行
From Callback 来自回调
undefined 未定义
var callback_function = function (funcArg) {
console.log("From Main Function");
setTimeout(funcArg("Test"), 10); // WATCH THIS LINE
console.log("From Main Function 2");
};
callback_function(function (arg) {
console.log("From Callback");
console.log(arg);
});
console.log("This should run before callback");
Output: 输出:
From Main Function 从主要功能
From Callback 来自回调
Test 测试
From Main Function 2 从主要功能2
This should run before callback 这应该在回调之前运行
Any idea why this is happening? 知道为什么会这样吗? And how can I run the function asynchronously despite passing in an argument?
尽管传入一个参数,我如何异步运行该函数?
You're not passing a function to setTimeout
but calling your function and passing the result. 您没有将函数传递给
setTimeout
而是调用函数并传递结果。
Change 更改
setTimeout(funcArg("Test"), 10);
to 至
setTimeout(function(){ funcArg("Test")}, 10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.