DEV Community

3BiEiD
3BiEiD

Posted on

Promises in Js

JavaScript Promise are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code.

Multiple callback functions would create callback hell (a chain of limitless callbacks inside each other) that leads to unmanageable code.

Promises are used to handle asynchronous operations in JavaScript.

Promises are objects that have four states :
1) Pending: The initial state which means not rejected nor resolved.
2) Fulfilled: This term refers to successful completion.
3) Rejected: means the promise cannot be fulfilled due to an error or some exceptional situations in asynchronous operations.
4) Settled: Promise has been fulfilled or rejected

You can decide what to do upon this promise either in the happy way or the errors way, so there are 2 methods to do so
then() and catch()

let promise = new Promise(function (resolve, reject) {
    const x = "test";
    const y = "test"
    if (x === y) {
        resolve();
    } else {
        reject();
    }
});

promise
    .then(function () {
        console.log('Success');
    })
    .catch(function () {
        console.log('Some error has occurred');
    });

Enter fullscreen mode Exit fullscreen mode

then() method can take 2nd argument, so you ignore catch()
The second argument is executed if the promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method

let promise = new Promise(function (resolve, reject) {
    resolve('test again');
})

promise
    .then(function (successMessage) {
        //success handler function is invoked 
        console.log(successMessage);
    }, function (errorMessage) {
        console.log(errorMessage);
    });
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post