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
});
2 Answers 2
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);
});
4 Comments
.bind method. async(foo.bind(null, param1, param2), function () {/*here the logic of the second callback */});, where param1 and param2 are the values you want to pass to foo. Documentation on bind .bind basically defines a dummy function that calls foo.You should pass foo instead of calling it while calling async:
async(foo, function () {
var check = checkField();
alert('Check: ' + check); //somehow never comes out
});