我正在尝试使用回调函数。我想让我的回调异步,据我了解,其中一种方法是调用 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");
输出:
来自主函数
来自主函数2
这应该在回调之前运行
来自回调
未定义
这不是异步的:
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");
输出:
来自主函数
来自回调
测试
来自主函数2
这应该在回调之前运行
知道为什么会发生这种情况吗?尽管传递了参数,但如何异步运行该函数?
最佳答案
您不是将函数传递给 setTimeout
,而是调用您的函数并传递结果。
改变
setTimeout(funcArg("Test"), 10);
至
setTimeout(function(){ funcArg("Test")}, 10);
关于javascript - 如果我传入参数,函数不会被异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676156/