🎶 Promise Me No Promises
Published: 2022-07-27 20:48:00


## `🎶 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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) => {
    const someResult = 'hello there!';
    resolve(someResult);
});somePromise.then(resultArg => {
    console.log(resultArg);
});](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/begss8rkfvbzdl5hnm1x.png)
 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z2c67ipkxseirh1mcsbv.png)
 

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gyft3k149048jg8v9984.png)
 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djr3wq6r4098owme8rvm.png)
 
## 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](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and now on [NodeJS!](https://blog.logrocket.com/fetch-api-node-js/)), which is a PERFECT use of Promises! Let's see how.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/br53ekoeuirzquxshzc0.png)

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](https://developer.mozilla.org/en-US/docs/Web/API/Response)).
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)](https://user-images.githubusercontent.com/4923719/180843703-9974952b-a5e8-4305-ae2b-de15400c4f41.png)

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

![carbon (2)](https://user-images.githubusercontent.com/4923719/180843601-7d81975d-c420-4dfa-8df3-3aeee3c4a2c2.png)

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)](https://user-images.githubusercontent.com/4923719/180843546-0cacf119-0d21-4af1-883d-cf7b3c15ac6c.png)

You can simply do:
![carbon](https://user-images.githubusercontent.com/4923719/180843471-1f6a1519-80b2-4e81-b579-19bf4c3b4637.png)

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 😄