• Meteor

Introduction: Meteor Fibers and Dynamics

From the class:  Meteor Fibers and Dynamics

In this class, we're going to talk about two key concepts that are underpinnings of the Meteor framework. The first is the ability to write synchronous code on the server, using a technology called Fibers. Usually in Node.js applications, when we connect with a database or do asynchronous I/O, we nest callbacks, like you see here. But Meteor allows us to write our code in a much nicer style, where we can take the result of a query to Mongo and just return it directly, without sacrificing the performance benefits that we get from asynchronous I/O and Node.js. Meteor does this by using a library called Fibers, which gives us co-routine support for Node.js.

The second key thing that Meteor provides on top of Fibers is the ability to have dynamically scoped variables-- that is, a variable that changes depending upon where you are in the call stack. Understanding these concepts is critical to understanding performance in Meteor, and also how to debug errors, like this one that you may have seen, that says that Meteor code must always run within a Fiber.

To learn these concepts, we're going to start off by reviewing what it means to be asynchronous in Node.js. We'll look again at the call stack and task queue, and what happens when we make an asynchronous call to read a file or make a network request, for example, to Mongo. Then we'll look at what a Fiber is, and how we can work with them, by debugging them on a server side debugger using node-inspector.

Once you know what a fiber is, we'll use them to take an asynchronous function and make it synchronous on the server, without sacrificing any performance benefits. Finally, we'll conclude the Fiber section by taking a look at the function Meteor provides us called bindEnvironment, which is the key to tying asynchronous code together with Meteor.

In the second part of the class, we'll look at how Meteor implements dynamic variables using something they call Meteor dynamics. First, I'll explain what a dynamic variable is, so you get some intuition. And then we'll play with a data structure called a Meteor environment variable that gives us an implementation of dynamic variables. And then we'll look at where Meteor uses those in the framework.

I think this is really one of the coolest parts of the Meteor framework. And spending time learning how these concepts work will make you a lot better at debugging your own code, but also understanding how the framework works. So, I hope you enjoy this class.