Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript asynchronous execution: will a callback interrupt running code?

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?

like image 470
mlihp Avatar asked Jan 13 '12 04:01

mlihp


1 Answers

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.

like image 61
jfriend00 Avatar answered Sep 23 '22 21:09

jfriend00