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();
AaronF
  • 2,841
  • 3
  • 22
  • 32
  • possible duplicate of [Node.js Event loop](http://stackoverflow.com/questions/25568613/node-js-event-loop) – Epicblood Jul 28 '15 at 20:04

2 Answers2

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");
});
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 2
    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. – leo.fcx Jul 28 '15 at 19:52
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.

Epicblood
  • 1,167
  • 2
  • 10
  • 29