简体   繁体   English

如果我传入参数,则不会异步调用函数

[英]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中将参数传递给我的回调,否则这很有效:

This is async: 这是异步的:

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 未定义

This is not async: 这不是异步的:

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.

相关问题 如果我传递参数,则不会调用javascript函数 - javascript function is not being called if i pass a argument 如何将参数传递给使用setTimeout调用的函数? - How can I pass an argument to a function called using setTimeout? 在href标签中调用参数时,如何将其传递给函数 - How can I pass an argument to a function when I have called it in the href tag 通过Javascript函数异步调用函数时,如何将参数传递给控制器​​中的函数 - How to pass a parameter to a function in controller when function is called asynchronously through a Javascript function 未在 nodejs 中异步调用的第二个函数 - Second function not called asynchronously in nodejs 我可以异步地将回调函数作为变量传递给多个级别吗? - Can I pass down a callback function as a variable multiple levels asynchronously? 将函数作为参数传递给在第一个函数中调用的另一个函数 - Pass function as argument to another function called inside the first one 如何使用处理程序将参数传递给 function? - How can I pass an argument into a function with a handler? 如何在此 function 中传递参数 - How do I pass a argument in this function 如何测试是否在异步调用的测试函数B中调用了函数A - How to test if function A was called inside the test function B if it was called asynchronously
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM