DEV Community

Cover image for JS Bites: Chapter 2 - Async Made Easy with Promises
Sanjay R
Sanjay R

Posted on

JS Bites: Chapter 2 - Async Made Easy with Promises

Promises
To overcome the issue of Callback Hell, we use Promises. In Promises, there are two main actors: the "Promise Maker" and the "Promise Receiver."

Promise Maker
The Promise Maker is the one who creates and returns the promise. It initiates an action that will eventually complete, either successfully or with an error.

Example:

function makePromise() {
    return new Promise();
}

Enter fullscreen mode Exit fullscreen mode

Promise Receiver
The Promise Receiver is the one who receives the promise from the Maker and performs actions based on its outcome.

Example:

let promise = makePromise();

Enter fullscreen mode Exit fullscreen mode

When a Promise is initially created, it enters the "pending" state. Then, it can either be fulfilled (completed) or rejected (encounters an error).

Creating and Handling Promises

function isOdd(number) {
    return new Promise((resolve, reject) => {
        if (number % 2 !== 0) {
            resolve(true);  // Resolve if the number is odd
        } else {
            reject(false);  // Reject if the number is even
        }
    });
}

const promise = isOdd(4)
    .then((result) => console.log(result))  // Handling fulfillment
    .catch((error) => console.log(error));  // Handling rejection

Enter fullscreen mode Exit fullscreen mode

Chaining Promises
Promises can be chained together, allowing for sequential execution of asynchronous operations. This is achieved by returning a Promise from within a .then() or .catch() block.

Example:

function asyncTask() {
    return new Promise((resolve, reject) => {
        // Asynchronous task
        resolve('Data from async task');
    });
}

asyncTask()
    .then((data) => {
        console.log(data);
        return anotherAsyncTask();  // Return another Promise
    })
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error(error);
    });

Enter fullscreen mode Exit fullscreen mode

Reject and .catch()
These are used to handle errors that occur during the execution of a Promise. If a Promise encounters an error, it gets rejected, and .catch() is used to handle that error.

Example:

const promise = isOdd(4)
    .catch((error) => console.log(error));  // Handling rejection

Enter fullscreen mode Exit fullscreen mode

Finally()
The finally() method is used to execute code after the Promise is settled, regardless of whether it was fulfilled or rejected. It's commonly used for cleanup tasks.

const promise = isOdd(4)
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .finally(() => console.log("Promise execution completed"));  // Executes regardless of fulfillment or rejection

Enter fullscreen mode Exit fullscreen mode

See you in the next chapter...

Top comments (0)