11
Meteor's Fibers
As I confessed in the previous chapter, I learned to program on Meteor, and for a long time asynchrony did not exist for me. A method on the server looked like this:
Meteor.methods({
transfer(from, to, amount) {
const a = Accounts.findOne(from);
if (a.balance < amount) throw new Meteor.Error('no-money');
Accounts.update(from, { $inc: { balance: -amount } });
Accounts.update(to, { $inc: { balance: amount } });
return Accounts.findOne(to).balance;
}
});
Not a single callback, not a single then, not a single await. Every line goes to the database, and the code reads like a textbook. An error thrown anywhere reaches the client, and try/catch works the way it should. Meanwhile the server ran on the same Node with its single thread, and while one method waited for the database, other clients were served. At the time I did not wonder how this worked.
It was built on the Fibers library. A fiber is a part of the program with its own stack; it can be suspended at any point and later resumed from the same place. In languages that have them, fibers are sometimes called coroutines or lightweight threads. Unlike real threads, fibers do not run at the same time: at any moment only one is running, and they switch only when the running fiber itself decides to wait.
Marcel Laverdet wrote node-fibers, a Node library that added such fibers to V8, and Meteor built its entire server on it. Each client request ran in its own fiber. When code inside a method went to the database, the driver sent the request and suspended the fiber together with its whole stack, and the event loop went off to serve others. When the response arrived, the fiber resumed, and findOne returned the result as if it had simply been waiting all along. For old libraries written in Node style, Meteor had a wrapper, Meteor.wrapAsync: it turned a callback-style function into a function that suspends the fiber and returns the result in the ordinary way.
Gratis, solo falta un paso
El resto del libro es gratis
Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.
¿Tienes cuenta INITE? Entra y el libro se abre sin correo.
No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.
Cómo se guarda la dirección