swizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

JavaScript promises are just like monads and I can explain both in less than 2 minutes

There's a joke in functional programming that once you understand monads, it becomes impossible to explain them to others. The amount of monad tutorials on the internet is growing almost exponentially 😁

Monads are a funky concept that's nearly impossible to understand in all of its nuance. Maybe I'm just not smart enough. That's why I'm not going to explain any of that.

Screw the mathematical definition. Look at this shit 👇

o.O wat O.o

Here's a handwavy explanation instead: Monads are like a bubble. They wrap your dirty values and protect the rest of your code from weird effects.

I used the continuation monad as an example because it is similar to JavaScript Promises. A way to talk about the future. 1

Let's pretend you're a mouse looking for the ultimate question to life, the universe, and everything. You build a super computer that will calculate the answer, and you call it Earth.

You know Earth will take around 4.54 billion years to calculate the question. But you're writing the code right now. You can't wait 4.54 billion years to finish your project.

What do you do? You put Earth in a time bubble.

Like this:

```.css-1yb0ye3{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-1yb0ye3 .comment,.css-1yb0ye3 .prolog,.css-1yb0ye3 .doctype,.css-1yb0ye3 .cdata,.css-1yb0ye3 .punctuation{color:#b6ad9a;}.css-1yb0ye3 .namespace{opacity:0.7;}.css-1yb0ye3 .tag,.css-1yb0ye3 .operator,.css-1yb0ye3 .number{color:#063289;}.css-1yb0ye3 .property,.css-1yb0ye3 .function{color:#b29762;}.css-1yb0ye3 .tag-id,.css-1yb0ye3 .selector,.css-1yb0ye3 .atrule-id{color:#2d2006;}.css-1yb0ye3 .attr-name{color:#896724;}.css-1yb0ye3 .boolean,.css-1yb0ye3 .string,.css-1yb0ye3 .entity,.css-1yb0ye3 .url,.css-1yb0ye3 .attr-value,.css-1yb0ye3 .keyword,.css-1yb0ye3 .control,.css-1yb0ye3 .directive,.css-1yb0ye3 .unit,.css-1yb0ye3 .statement,.css-1yb0ye3 .regex,.css-1yb0ye3 .at-rule{color:#728fcb;}.css-1yb0ye3 .placeholder,.css-1yb0ye3 .variable{color:#93abdc;}.css-1yb0ye3 .deleted{text-decoration-line:line-through;}.css-1yb0ye3 .inserted{text-decoration-line:underline;}.css-1yb0ye3 .italic{font-style:italic;}.css-1yb0ye3 .important,.css-1yb0ye3 .bold{font-weight:700;}.css-1yb0ye3 .important{color:#896724;}.css-1yb0ye3 .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}```function getQuestion() {
return Earth()
.then((ArthurDent) => ArthurDent.subconscious())
.then((subconscious) => Scrabble.output(subconscious))
}
``````

In The HitchHiker's Guide to The Galaxy, Arthur Dent was the final result of a 4.54 billion year calculation. He mindlessly picked letters out of a pile of Scrabble™ tiles, and the result produced the ultimate question.

That means our `getQuestion` function first constructs an Earth, then gets `ArthurDent`, accesses his subconsciousness, and uses Scrabble™ to print the result. 🤙

Here's what that looks like in practice:

Let's compare promises to callbacks. You're likely to have met with callbacks before, JavaScript is full of them.

``````let theFuture = function (callback) {
setTimeout(callback, 5000)
}

theFuture(() => {
console.log("It is now 5 seconds later")
})
``````

We turn `theFuture` into a Promise and trigger its `resolve` method after 5 seconds. The `Promise` wrapped everything inside its body into a protective time bubble.

With a promise, we can pass `theFuture` around and do all sorts of stuff. But if we want to access the future, we have to use `.then` and give it a function.

When I first saw this, I thought "So what's the big deal? This is the same as callbacks.”

So here's the big deal: Once you're in a promise, you're always in a promise. Because promises are like monads 😁

Check out this simplified real world example from my day job.

``````makePurchase(){
this.paymentView
.fetchPaymentInfo()
.then(paymentInfo  => this.finishPurchase(paymentInfo))
.then(token => this.showSuccessModal())
.catch(error => console.error(error));
}

fetchPaymentInfo(){
if (this.paypal) {
return this.getPaypalPaymentInfo(); // returns promise
}else{
return this.getCCPaymentInfo(); // returns promise
}
}

getPaypalPaymentInfo(){
return this.brainTreeClient
.tokenizePaypal()
.then(response => {
return response.paymentInfo;
});
}

finishPurchase( paymentInfo ) {
return fetch('/purchase/path')
.then(response => response.json())
.then(json => {
if (json.token) {
return json.token;
}else{
throw new Error("Purchase failed")
}
});
}
``````

Don't worry about the behind-the-scenes details of that code. Here's what you should focus on:

1. The main `makePurchase` function does everything through Promise access. The `.then` and `.catch` methods are like peeking into the Promise time bubble. You're saying: Once this time bubble resolves, I want to do so and so with the result.
2. The `fetchPaymentInfo` is the first method in our chain that creates a Promise. From then onwards, we can access returned values only through `.then` and `.catch`. It uses `getPaypalPaymentInfo` and `getCCPaymentInfo` to talk to Braintree, which is an operation that takes some time.
3. `braintreeClient.tokenizePaypal()` returns a promise. There's no need to wrap this in another Promise inside `fetchPaymentMethod`. You can return it like any normal value.
4. `getPaypalPaymentInfo` uses `.then` to look into the Braintree response. Since you're in a Promise, you can `return` flat values without worry. They're already wrapped in a Promise.
5. As a result, we can chain multiple `.then` calls in `makePurchase`. Some methods return a regular value, some return a Promise. JavaScript don't care, it's all the same because everything returned from a Promise is a Promise.

And that's why Promises are just like monads.

Oh, and error handling. Don't worry about that either. As long as there's a `.catch` call somewhere in the chain, you're good. Errors bubble up through the chain of Promise look-into-s until they encounter a `.catch`.

Hope that helps, it took me months of practice to grok 🤓

1. Technically continuations are more similar to callbacks, but bear with me.
Published on September 21st, 2017 in Technical, JavaScript

Continue reading about JavaScript promises are just like monads and I can explain both in less than 2 minutes

Semantically similar articles hand-picked by GPT-4

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

Created by Swizec with ❤️