DEV Community

kanaga vimala
kanaga vimala

Posted on

Understanding JavaScript Promises: A Beginner’s Guide.

What is promise in JS?

A promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation. It is used for handling asynchronous operations, such as making API calls or reading files, in a more organized and readable way. Promises have three states: Pending: The initial state.

JavaScript Promise Object

A Promise contains both the producing code and calls to the consuming code.

How to Create a Promise

You create a Promise using the Promise constructor, which takes a function called the executor. This function receives two arguments: resolve and reject. You call:

resolve(value) if the async operation succeeds.

reject(error) if it fails.
Enter fullscreen mode Exit fullscreen mode

**
Promise Syntax**

new Promise ((resolve,reject) => {
const password = true;

        if (password) {
    resolve();
        }
        else
        {
            reject();
        }
    })

    .then(success)
    .catch(failure)
    function success(){
Enter fullscreen mode Exit fullscreen mode

console.log("sucessfully login");

    }
    function failure(){
    console.log("invalid login");

    }
Enter fullscreen mode Exit fullscreen mode

**
Promise Three States**

Pending — initial state, the operation hasn’t completed yet.

Fulfilled (Resolved) — the operation completed successfully.

Rejected — the operation failed.
Enter fullscreen mode Exit fullscreen mode

**
Why Use Promises?**

Avoid “Callback Hell”: Before Promises, callbacks inside callbacks made code hard to read and maintain.

Better Error Handling: With .catch(), you can handle errors cleanly in one place.

Chainability: You can chain multiple .then() for sequential async tasks.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)