Callback, Promise, Observable, and Doughnuts

This is the story of Jerry JavaSript's Automated Slow Doughnut Shop.

One day, I wanted a doughnut. So I rode my bike to the automated slow doughnut shop, where they have a slow doughnut machine. You put in a dollar. And then the machine mixes batter, heats the fat, drops the batter into the fat, lifts it out on a linked metal conveyor belt, dusts it with sugar, and drops it into your waiting hands.

Once I get my doughnut, I can eat it in the usual manner. But from the time I put in my dollar until the time I receive my doughnut, I am blocked.

Fortunately, the slow doughnut machine has a slot labeled, "Insert callback here".

This is great. I code up a function eatDoughnut(doughnut). I can reference my teeth, esophagus, stomach, and so on, because they are mine and I know all about them. And then I slip my  eatDoughnut(doughnut) function into the slot and get on my bike and ride  to the office while the slow doughnut machine is still mixing batter.

When the doughnut is ready, the machine calls my personal eatDoughnut(doughnut) function and I am happy.

The next day, I'm passing the slow doughnut shop and want to get a doughnut for my friend Bob at the office. Fortunately, the slow doughnut machine has a new feature. "Doughnut Promise, $1".

I put in my dollar and the machine dispenses a Promise, which is a silver sphere about the size of a basketball with an antenna on top, and a slot labeled "then" on one side. But of course, everyone knows what a Promise looks like.

Without waiting around, I put the promise in my basket and ride to the office. Bob is away at the moment, but I put the promise on his desk. And to avoid confusion, I label it with a post-it saying "doughnut".

Bob returns to his desk, quite hungry. Seeing the promise of a doughnut, and of course knowing how promises work, he codes up his own function. He calls it gobbleDoughnut(doughnut). And it refers to his own teeth, esophagus, stomach, etc.  ...frankly, things I'd rather not know about.

Bob slides his gobbleDoughnut(doughnut) function into the "then" slot and, sooner or later, Bob gets a doughnut.

The next day, I will be working late and Bob kindly does me a favor. He stops by the slow doughnut shop and feeds money into the machine next to a sign that says, "Doughnut Observable, $5".

The slow doughnut machine emits an Observable, which is like a Promise, but larger, and less round. It has a slot labeled "subscribe".

Bob arrives at the office and tosses me the Observable. The Observable is much like the Promise, but better. When  I insert my own eatDoughnut(doughnut) function into the "subscribe" slot, I receive multiple doughnuts, arriving over time as the machine cooks them.

Doughnuts for everyone! No waiting around! And we all remain blessedly ignorant of each other's inside parts.

Thank you.




Comments

Popular posts from this blog

Learn grid and grid-template-areas FIRST!!!

The Day TDD Started Working for Me