DEV Community

Cover image for ๐ŸŽถ Promise Me No Promises
Patrick Canella
Patrick Canella

Posted on • Updated on

๐ŸŽถ Promise Me No Promises

๐ŸŽถ Promise Me No Promises ๐ŸŽถ

(okay, I'm done...)

In JS what are they? If you're a beginner in JS you already should have some knowledge of callbacks and how they work. If not let me know and I can make a blog post on these as well.

Anyway, what is a Promise?

Well, MDN defines a Promise as:

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Ok, those are some words. Let me give an example of a basic Promise and then kind of go over what it means.

const somePromise = new Promise((resolve, reject) => {<br>
    const someResult = 'hello there!';<br>
});somePromise.then(resultArg => {<br>

This is a really basic promise. Basically what we are doing here is saying "hey when this promise gets resolved, we are going to print out hello there. Easy, right? But why would I use a Promise for this, when I can just do:

console.log('hello there!')?

Great point! Promises aren't really needed or used for something like this. So what are they used for?

Promises are used to wrap asynchronous functions (like HTTP requests) and give its result in a synchronous manner

Yes yes, we all know that JS is asynchronous, but if we don't have something like promises, we'll be doing what in the JS community we like to call ๐Ÿ”ฅ๐Ÿ”ฅ CALLBACK HELL ๐Ÿ”ฅ๐Ÿ”ฅ. Callback hell is when you are calling many functions whose results come in the form of a callback with an argument as a value... something like this:

Image description

YIKES. What a mess. This is how we used to have to write JS! This simplified version below uses Promises.

Image description

As you can see we wrap the existing async fs.readdir function in a Promise and once fs.readdir has completed, we get the result via resolve

BTW, resolve is just a fancy way of using return in a Promise. It basically says "hey here's the data you are looking for, I'm going to return this in the callback. reject is similar, but will only print out the err when the you put a .catch method at the end of the chain. Let's take a look at what that would look like:

Image description

That's great, but what's a real world example of this?

Great question! In JS, we have the ever famous fetch function (both on the browser and now on NodeJS!), which is a PERFECT use of Promises! Let's see how.

Image description

So what just happened? A few things, as mentioned in the code comments:

  1. We initially make the fetch call with the URL as its parameter. This kicks off an async function that will return a Promise and "resolves" as a Response type (more on that here).
  2. Once that fetch completes or resolves, we want to use then to get the response object.
  3. With the response object, we now want to make this response into a JSON format. Thus, we call response.json(). We'll set this to a variable, so we can use it in the next line.
  4. Once response.json() has completed, we use the final then to print out the JSON body that we are looking for.

and ta da! You get this as a result:

carbon (3)

Honestly, this is broken down a bit much. Usually for a simple fetch request, you can shorten it with chaining like so:

carbon (2)

And that's it! Promises provide a great alternative to Callback hell and are great for async functions of any kind.

Actually, one more thing...

With ES6, the introduction of async/await has made Promises even easier than before! I'll probably do a separate blog post on this, but in essence instead of doing:

carbon (1)

You can simply do:

No then needed! This is some nice syntactic sugar that JS provides now so we can write our code more linearly like many synchronous languages can do. It's incredibly useful and you'll see most promises written in this way.

Anyway, I hope this helps you understand how promises work. Let me know if you have any questions! Thanks for reading ๐Ÿ˜„

Top comments (0)