DEV Community

Cover image for Promises in JavaScript for Beginners
Shubh Sharma
Shubh Sharma

Posted on • Updated on

Promises in JavaScript for Beginners

Intro

When working with async code in javascript you sometimes need to wait for the code to return data before further processing of data.

For example: reading a file takes some times or fetching data from the server can take time and since this is async task it gets delegated.

However we need this data before we can process and do anything further in our code. This is where promises can be super helpful.

What is a Promise?

Before promises were introduced, managing asynchronous operations was done using callbacks.

Callbacks are functions that are passed as arguments to another function and are executed later, once the asynchronous operation is complete.

However, as programs grew in complexity, managing callbacks became challenging, leading to what's often referred to as "callback hell" or "pyramid of doom."

This is a situation where nested callbacks make the code hard to read and maintain.

Promises were introduced to address these issues and provide a better/cleaner way to handle asynchronous operations.

So what the heck is a Promise? well, a promise is an object representing the eventual completion or failure of an async operation and its resulting value.

In short if an async task is completed with success it returns a resolve object with the data and if the task fails it returns a reject object with an error. Promise ensures that once the operation is completed, you can do anything you wanted depending on the completion or failure of the operation.

States of a promise

A Promise has three states:

  1. pending: Promise is pending and its neither resolved nor resolved
  2. resolved: Once promise is resolved it returns data to then() method
  3. rejected: Once promise is rejected the error is returned to catch()

A basic example of a promise used:

// Creating a promise 
let myPromise = new Promise((resolve, reject) => {
    // Simulating async operation using setTimeout
    setTimeout(() => {
        let success = true;
        if (success) {
            resolve("Data fetched successfully");
        } else {
            reject("Error fetching data");
        }
    }, 2000);
});
Enter fullscreen mode Exit fullscreen mode

This piece of code means a new promise is created which does an async operation such as setTimeout() and once its completed it either resolves the promise which means success or it gets reject with an error.

Once created a promise you can consume that promise.

// Consuming the promise
myPromise
.then((result) => {
    console.log(result);
})
.catch((error) => {
  console.error(error);
})
//default one, gets executed no matter resolve or reject
.finally(() => {});
Enter fullscreen mode Exit fullscreen mode

If the promise is resolved then it is returned to .then() method of that promise, if promise is rejected then it gets returned to .catch() method.

In both the cases, you can do a task after the promise is completed.

How to handle data returned by the promise?

This can be done with the help of chaining of then() and catch()

Once the data is returned from the resolve you can get that data in then() method and then return it into a new then chain and then you can use that data and the error is caught by catch() method.

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {}
       const error = false;
        console.log("Async task completed!");
        //data returned with resolve
        if(error === false) resolve([1,2,3]);
, 1000);
});

//handling data with chaining of then() and catch()
promise.then((data) => {
    return data;
})
.then((data) => {
    console.log(data.splice(0, 1));
})
.catch((err) => {
    console.log(err);
})
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
oculus42 profile image
Samuel Rouse

Nice article! This is a solid introduction to promises.

However, there is an error in your last code example.

// argument "data" and return "response" don't match
promise.then((data) => {
    return response;
})
Enter fullscreen mode Exit fullscreen mode

This should either receive response as the argument, or return data. Either way, if it returns the original value the entire .then() is not necessary.

If you are interested in some more suggestions for working with Promises, I wrote an article called Promises: Five Tips to Work Smarter

Collapse
 
shubhsharma19 profile image
Shubh Sharma

Fixed it, thanks for the update! :)

Collapse
 
corners2wall profile image
Corners 2 Wall

You inspired me to write an article. Thank you

Collapse
 
shubhsharma19 profile image
Shubh Sharma

Thankyou for reading! :)

Collapse
 
Sloan, the sloth mascot
Comment deleted