Reputation: 667
I tried to write asynchronous function calls in javascript using setTimeout
function async(fn, callback) {
setTimeout(function () {
fn();
callback();
}, 1000);
}
This is how the function is being called. I want function foo() to run first, and then my next function. Foo() runs successfully but the next function never comes out. Any idea?
async(foo(), function () {
var check = checkField();
alert('Check: ' + check); //somehow never comes out
});
Upvotes: 0
Views: 371
Reputation: 26901
You should pass foo instead of calling it while calling async:
async(foo, function () {
var check = checkField();
alert('Check: ' + check); //somehow never comes out
});
Upvotes: 2
Reputation: 18522
You're calling foo
in a synchronous way, because instead of passing a reference to foo
to the async
function, you're calling foo
and passing to async
the result of foo
, which is probably undefined
(although just guessing here, because I don't know how foo
looks like), so when the timeout hits and async
tries to call fn
it throws error that undefined
is not a function and thus never reaches the line that calls the second callback.
You should call async
this way:
async(foo, function () {
var check = checkField();
alert('Check: ' + check);
});
Upvotes: 2