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. This works well, unless I try to pass an argument to my callback in 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
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
This should run before callback
Any idea why this is happening? And how can I run the function asynchronously despite passing in an argument?