Promises

Promises

Everything about using promises in modern javascript

ยท

4 min read

What the heck are promises in javascript?

First of all, javascript is so beautiful and powerful, I can go on for like an eternity talking about it, but if you are here, then you already are in love with javascript right?

image.png

Obviously javascript ๐Ÿ˜‡๐Ÿ˜Š

Enough ranting about javascript, let's go over the main topic at hand which is Promises. let's go over the definition of promises together so that we can be on the same page while going through the blog.
According to the docs=>
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. So, not gonna lie, when I first started with promises, it was all over the place but that's why I am here to make your lives easy ๐Ÿ˜† Firstly, What is async(asynchronous) operations, so async operations are the code that doesn't get executed in a single-threaded fashion(in a single lifecycle) just like any normal code would run, So essentially it basically means that whenever you want to perform some tasks that you want to run after the page is rendered to the screen.
Let's go over all the stages of promises;
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.

// promise structure: 
const promise = new Promise((resolve, reject) => {
  if (1 + 1 === 2) {
    resolve("you have successfully performed your task"); 
  } else {
    reject("error while resolving the promise");
  }
});

promise.then((res) => console.log(res)); // you have successfully performed your task

YAY!!! ๐Ÿ˜Š We made our first promise, as you can see it is a contrived example but you get the gist that you can essentially do anything in the promise callback function to resolve and reject. one more thing we can catch errors which we didn't do in the first Example;

// handling errors: 
const promise = new Promise((resolve, reject) => {
  if (1 + 1 === 3) {
    resolve("you have successfully performed your task"); 
  } else {
    reject("error while resolving the promise");
  }
});

promise.then((res) => console.log(res)).catch((err) => console.log(err));
 //error while resolving the promise

This means that we catch an error by using chaining a catch function in the promise call. Now lets see an Real world example where promises can be helpful,
let's make a dad joke fetcher app that fetches a joke when we press a button. Interesting right?
let's Go...

<body>
    <div id="app">
      <h1 id="joke">
       Please fetch jokes by clicking the button
      </h1>
    </div>
    <button id="button">New Joke</button>

    <script src="src/index.js"></script>
  </body>

image.png We would not add any CSS as at this point we are not caring about CSS, we have to focus on building the functionality.

Lets hook all the elements in index.js file so that we can use it.

const jokeEl = document.querySelector("#joke");
const jokeBtn = document.querySelector("#button");

Let's create our main function for fetching the dadJoke:

function fetchingJoke() {
  const result = fetch("http://icanhazdadjoke.com", {
    headers: {
      Accept: "application/json"
    }
  })
    .then((res) => res.json())
    .then((data) => data);
  return result;
}

So, not to overwhelm you with so much code, let's break it down line by line, firstly, let's understand the fetch function
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. This basically is used for using HTTPS methods like GET, POST, DELETE, etc. So that we can communicate with the server in an async fashion so that the data can be fetched from the server Also, fetch return a promise which make it easy to chain a .then for getting the response as resolved or rejected.
we would not learn about the headers for now, as it is out of the scope. So now as you can see we return the result so as it is a promise we will have to chain a .then so that we can catch the promise for getting our data and displaying it.

function handleClick() {
  fetchingJoke().then((data) => {
    jokeEl.textContent = data.joke;
  });
}
jokeBtn.addEventListener("click", handleClick);

image.png

So, In this way we can use promises in a real code where we can fetch data to display on the page.

Here's the code sandbox link: Link

ย