1

In the following code, I'm attempting to understand the concept of writing asynchronous JavaScript functions. To be clear on my assumptions:

The function logTest() is called. It calls asyncTest(), passing in the log() function. However, asyncTest() doesn't call log() directly. Rather, it passes it to the event queue to be called when the stack clears. The stack shouldn't clear until after the for loop completes, writing twenty "waiting..."'s. However, the console output puts the "async" line first before the for loop. I ran this code in Node.js, in which console.log is a synchronous function. Does anyone know why the "async" line wasn't written last?

function asyncCall(method) {
  return setTimeout(method, 0);
}

function log(str) { console.log(str); }

function logTest() {
  asyncCall(log("async"));
  for(var i = 0; i < 20; i++) {
    log("waiting...");
  }
}

logTest();
1

2 Answers 2

4

That's because you're passing the result of log("async") rather than the function log to asyncCall.

Basically, it executed log("async") (logging "async" to the console prior to executing asyncCall). The result of the call (which is undefined since log doesn't return anything) is passed to asyncCall. Then async call gets executed.

You may want to change that to:

asyncCall(log.bind(null, "async"))

or

asyncCall(function(){
  log("async");
});
Sign up to request clarification or add additional context in comments.

1 Comment

This does not answer the question about asynchronous execution. He is expecting the 'async' string printed after the lines printed in the loop, which is not a correct assumption.
0

you are not passing in log("async") you are calling it and passing the result into asyncCall()

as soon as you add () you are (usually) calling a function. As Joseph mentioned, you can pass in either log.bind(null, "async") (although I prefer binding this), or you can pass in a new function that calls log("async") by doing something like:

asyncCall(function(){
  log("async");
}); 

However, to answer your real question, your assumption that "async" will be printed after 20 "waiting..." is incorrect. In order to better understand the event queue, i suggest you read this

basically, even though node is technically single threaded, it acts kind of like a multi-threaded application, so it can act as if it does many things at once.

2 Comments

This does not answer the question.
@leo.fcx just realized you are right, will update my answer

Your Answer

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.