Understanding JavaScript Promises in a dummy way.

Understanding JavaScript Promises in a dummy way.

A brief explanation about promises.

ยท

7 min read

Promises are used to handle asynchronous operations in JavaScript. JavaScript promises are not hard. However, most people find them a little bit hard to understand at the beginning. Therefore, I want to explain promises in a dummy way.

A Promise represents the eventual completion or failure of an asynchronous operation and its resulting value. A promise is a JavaScript object that links producing code and consuming code. Producing code is code that can take some time. Consuming code is code that must wait for some time.

When the executing code obtains the result, it should call one of the two callbacks:

  • resolve(value): If the promise is resolved successfully, the result is the value

  • reject(error): If an error occurred, error is the error object.

The promise object supports two properties:

  • state: Initially pending, then changes to either fulfilled when resolve is called or rejected when reject is called.

  • result: Initially undefined when the promise object is pending, then changes to value when the promise object is fulfilled or error when the promise object is rejected.

Benefits of Promises

  1. Improves code readability.

  2. Better handling of asynchronous operations. They can handle multiple asynchronous operations easily.

  3. Better error handling. They provide better error handling than callbacks and events.

How Promises work in brief

A Promise has three states. A Promise is in one of these states:

  • Fulfilled: The action related to the promise succeeded. resolve() will be called.

  • Rejected: The action related to the promise failed. reject() will be called.

  • Pending: The action related to the promise has not been fulfilled or rejected yet. This is the initial state before the promise succeeds or fails.

For example, when we request data from the server by using a promise, it will be in a pending state until we receive the data. When we get information from the server, the promise will be resolved successfully but if we don't get the information, the promise will be in the rejected state.

Once a promise has been called, it will start in a pending state. The calling function continues executing while the promise is still pending until it resolves to give the calling function whatever data was requested.

The created promise will eventually end in a resolved state, or in a rejected state calling the respective callback functions passed to then and catch upon finishing.

How to create a promise.

A promise can be created using the Promise constructor which you initialize using new Promise(). It takes two parameters, one for success(resolve) and the other for failure(reject). There will be a condition. If the condition is met, the Promise will be resolved, otherwise, it will be rejected.

For example, imagine if your mummy promises to buy you a new car when you get good grades. If your grades are good, your mummy is happy, and vice versa. So if she is happy with your grades, she will buy you the new car.

let goodGrades = true;

const doYouHaveGoodGrades = new Promise((resolve, reject) => {
    if (goodGrades) {
      const success = "Congratulations, here is your new car!";
      resolve(success);
    } else {
      const failure = "Sorry, next time maybe!";
      reject(failure);
    }
});

As you can see the promise checks the goodGrades global constant and if it's true, the promise goes to a resolved state because the resolve callback was called, otherwise the reject callback is called that puts the promise in a rejected state. If none of these functions is called, the promise will remain in a pending state.

How to use or consume a promise.

So we have created our first Promise. Now let's see how we can use or consume it. Promises can be consumed by using .then and .catch methods on the functions.

.then()

then() is invoked when a promise is either resolved or rejected. then() method takes two functions as parameters. The first function is executed if a promise is resolved and a result is received. The second function is executed if a promise is rejected and an error is received. The second function is optional because there is a better way to handle errors on promises using the .catch() method.

The syntax is:

promise.then(
    function(result) { /* handle success */ }
    function(error) { /* handle error */ }
)

.catch()

.catch() is invoked when a promise is rejected. catch() method takes one function as a parameter that is used to handle errors or promise rejections or failures.

Syntax:

promise.catch(
    function(error) { /* handle error */ }
)

Example

const doYouHaveGoodGrades = new Promise((resolve, reject) => {
    if (goodGrades) {
      resolve("Congratulations, here is your new car!");
    } else {
      reject("Sorry, next time maybe!");
    }
});

const checkGoodGrades = () => {
    doYouHaveGoodGrades
        .then(result => {
           console.log(result);
        })
        .catch(err => {
           console.log(err);
        });
}

In the example above, the then() method is only for resolved promises and if the promise fails, we use the catch() method. So if the promise gets rejected, it will jump to the catch() method.

Conclusion.

This article is just an introduction to promises about how to create a promise and how to use or consume a promise. I hope you found it useful and got an idea about JavaScript promises and how to use them.

Thanks for reading!!