DEV Community

Dev Ananth Arul
Dev Ananth Arul

Posted on

Promise in JavaScript

Promise:
A JavaScript Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows for handling asynchronous tasks in a more structured and readable way compared to traditional callback-based approaches, especially when dealing with multiple sequential asynchronous operations (callback hell).

1. Promise creation

resolve() → tells that the task was successful.

reject() → tells that the task failed.

2. Promise consumption

.then() → runs when resolved (success).

.catch() → runs when rejected (error).

.finally() → always runs at the end (success or failure)

Example:

<script>

        function task(step, result) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    console.log(step);
                    if (result) {
                        reject();
                    }
                    else {
                        resolve();
                    }
                }, 1000);
            })
        }
        task("Analysis")
            .then(() => task("plan"))
            .then(() => task("Design"))
            .then(() => task("Development"))
            .then(() => task("Testing", true))
            .then(() => task("Deployment"))
            .catch(() => console.log("Testing failed"))
            .finally(() => console.log("hello"))
    </script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)