0

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
});
asked Jan 18, 2017 at 21:48

2 Answers 2

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);
});
answered Jan 18, 2017 at 21:52
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but what if there is a parameter for foo and I need to pass that parameter before calling async?
@ichachan In this case use .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
Thanks but for some reason now foo is never called, even though the function runs successfully with the defined parameter. I make it call a dummy function instead and execute foo beforehand like this: foo(parameter); async(dummy), function () { var check = checkField(); alert('Check: ' + check); //now this is working });
@ichachan Without seeing your code it's difficult to say what is the issue. Please see this JSFiddle example which defines two callbacks with pre-defined params. .bind basically defines a dummy function that calls foo.
2

You should pass foo instead of calling it while calling async:

async(foo, function () {
var check = checkField();
alert('Check: ' + check); //somehow never comes out
});
answered Jan 18, 2017 at 21:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.