8

I was just hoping someone could clarify this for me. If I have the following code running server-side with node.js, not in a browser:

console.log("a");
db.get('select * from table1', function(result){
console.log("b");
});
console.log("c");

Presuming the database call is asynchronous I should get the result

a
c
b

But if i were to add the following line to the bottom of my code

while(1);

Then b would never execute, am I right?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
mlihp
  • 485
  • 4
  • 12
  • Are you talking about client or server javascript? – jfriend00 Jan 13 '12 at 04:31
  • We'll I did mean server side with node.js but I assumed it would be the same, am I mistaken? Is javascript always single threaded? – mlihp Jan 13 '12 at 04:34
  • @PhilM No, it isn't. node.js can and does use lots of threads. – cheeken Jan 13 '12 at 04:45
  • Good question. What happens when you try it? I hope you don't mind, but I edited the question slightly to make it more obvious you are talking about server side node.js: I'm hoping this will avoid more cases of people posting an answer about a browser and then deleting it (like I did - I didn't see the node.js tag at first). – nnnnnn Jan 13 '12 at 04:45
  • [This article](http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/) probably helps your understanding of the Node.js threading model. –  Jan 13 '12 at 04:48

1 Answers1

7

If you're talking about client-side javascript execution, you are correct (until the browser decides to stop your infinite loop).

Client-side javascript is single threaded so an asynchronous ajax call callback will not execute until the main stream of execution is done and a new stream of javascript execution can be started for the ajax event which will result in calling your ajax callback function.

You can read more about how javascript uses an event queue to serialize all events in this post.

Edit

I see from your edit that you're talking about server-side node.js, not browser code. By default, your callback is not going to run in a new thread so it will either execute immediately as part of the db.get() function call or more likely will not execute until your current stream of execution is finished and then the db.get() call is also completed and then the callback can be executed.

node.js does use threads in some situations and does use threads internally, but not in this type of situation.

Here's an good article on threading in node.js.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979