Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor threading style clarification

Tags:

meteor

Meteor's documentation states:

In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node

Do they actually mean?

A) the server is running multiple threads in parallel (which seems unusual within the Node.js ecosystem)

or

B) There is still only a single thread within an evented server and each request is processed sequentially, at least until it makes calls to resources outside the server - like the datastore, at which point the server itself is handling the callbacks while it processes with other requests, so you don't have to write/administer the callbacks yourself.

like image 481
Brad Murray Avatar asked Aug 02 '12 05:08

Brad Murray


1 Answers

Brad, your B is correct.

Meteor uses fibers internally. As you said, there's only one thread inside an evented server, but when you do (eg) a database read, Fibers yields and control quickly gets back to the event loop. So your code looks like:

doc = MyCollection.findOne(id);

(with a hidden "yield to the event loop, come back when the doc is here") rather than

MyCollection.findOne(id, function (err, doc) {
  if (err)
     handle(err);
  process(doc);
});

Error handling in the fiber version also just uses standard JavaScript exceptions instead of needing to check an argument every time.

I think this leads to an easier style of code to read for business logic which wants to take a bunch of actions which depend on each other in series. However, most of Meteor's synchronous APIs optionally take callbacks and become asynchronous, if you'd like to use the async style.

like image 199
David Glasser Avatar answered Sep 30 '22 20:09

David Glasser