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?
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?
Share Improve this question edited Jan 13, 2012 at 4:42 nnnnnn 150k30 gold badges209 silver badges247 bronze badges asked Jan 13, 2012 at 4:26 mlihpmlihp 4854 silver badges12 bronze badges 5- Are you talking about client or server javascript? – jfriend00 Commented Jan 13, 2012 at 4: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 Commented Jan 13, 2012 at 4:34
- @PhilM No, it isn't. node.js can and does use lots of threads. – cheeken Commented Jan 13, 2012 at 4: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 Commented Jan 13, 2012 at 4:45
- This article probably helps your understanding of the Node.js threading model. – user244343 Commented Jan 13, 2012 at 4:48
1 Answer
Reset to default 7If 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 pleted 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.