Definitive Guide to Promises in Node JS With Examples

Node JS differs from other programming languages as it contains asynchronous factors, leading to unexpected behaviour of the code. To put things in perspective, it is anything but sequential and therefore, as developers, you will need to work on it with a different approach. Let's study in detail in the blog:

Image
Published 1 Nov 2021Updated 10 Jul 2023

What is the Meaning of Promise in Node js?

Defined as an ? “A promise is a word taken for some action, which the other party who gave the promise might fulfill it or deny it”. This common programming feature was introduced in the ECMAScript 2015. It is an object holding a state that represents the completion or the failure of an asynchronous operation and the resulting value.

During fulfilling, the promise gets resolved, and in another case, it gets rejected. These are kind of design patterns, which can effectively remove the use of unintuitive callbacks in Node.js.

To sum it up, a promise is in either of the three states:

  1. Pending state — This is the initial state of the promise
  2. Resolved — This represents a successful operation
  3. Rejected — This represents a failed operation

Note: When the promise is resolved or rejected, it can never change.

All in all, the mainstay of a promise is its return value. These return values are non-existent when you work with the regular callbacks in Node.js. Promises offer more control on how to define the callback function due to the return value. That is perhaps, one of its main advantages.

During the development life cycle, there can be an instance, when multiple callback functions need to be nested together. Surely, you don’t want to encounter a messy situation. This is where you will need to alleviate the issue with a Promise.

That said, here’s the basic node js promise example:


let promise=performAync()
promise.then(onResolved, onRejected)

The “performAync” refers to a callback or asynchronous function, which are usually there for certain types of processing. In this instance, when the callback is being defined, the returned value will be called a Promise. The returned promise can have two outputs.

It should be noted that the core component of a promise object is the then method. It is the way to get a return value or the exception from any asynchronous operation. then takes two optional callbacks as the arguments — resolve and reject.

Any of the operations have the chances of being successful. In this case, it is denoted by the parameter ‘resolve’. But when there’s a chance of an error, it is denoted by the ‘reject’ parameter.

Here’s how an asynchronous Node callback takes place:



performAync(function(data, err)=>{


if (err) return console.error(err)


console.log(data)
})

When your“performAync”function returned a promise, the same logic will be written as:


let promise=performAync()

promise.then(console.log, consoler.error)

Why Promise is Used in Node js and What is the Advantage?

Asynchronous coding can terribly affect the readability of the code. This makes it difficult to break it into bite-sized, independent pieces. As a result, the code becomes more error-prone and developers tend to find it excruciatingly hard to make changes to it in the future.

Promises in Node js makes it simple for the developers to write asynchronous code in a manner that it is almost like the synchronous coding.

  • It allows the async call to return a value just like the synchronous function.
  • No, don’t need to run extra checks or try/catch for the error handling.
  • The code provides reusable independent functions.
  • It catches specific exceptions, therefore, helps display multiple error messages.

Summing up the key advantages, Node js promise offers the following benefits:

  • Enhanced readability
  • Reduced coupling
  • Better exception handling
  • Improved error-handling
  • Well-defined control flow
  • Functional programming semantics

How to Construct a Promise — Everything You Wanted to Know

How to Create Custom Node js Promises?

To construct the promise, use new Promise.

This is in the pending state. Next up, provide the constructor a factory function. This function is going to do the actual work. The function is called with the two arguments — resolve and reject. In the first case, it resolves the promise and in the second case, it rejects the promise. When the operation completes its course, the appropriate function can be called.

As mentioned earlier, instead of using an original callback mechanism, the code here creates a Promise object.

//syntax


let customPromise=new Promise((resolve, reject)=>{

….

})

//example

function addNumbers(allowToAdd,num1, num2){

return new Promise((resolve, reject)=>{

allowToAdd ? resolve(num1 + num2):reject(‘Fail To Add’)

});

}

//Handle result

let addResult=(value)=>{

console.log(“Add result :” + value)

}

let failResult=(failString)=>{

console.log(failString)

}

//consuming or calling promise

addNumbers(true,10,20).then(addResult,failResult)

//Result

Add result :30

As per the above example, “ addNumbers” method return promise object, either in “ resolve” or “ reject” stage depending upon the conditions.

The .then() method in a Promise must adhere to the following rules:

  • Both onResolved() and onRejected() are optional.
  • If the arguments supplied are not functions, ignore them.
  • onResolved() will be called after the promise is resolved. The promise’s value is the first argument.
  • The onRejected() will be called post the promise is rejected. The reason for the rejection will be the first argument.
  • onResolved() and onRejected() should not be called more than once.
  • .then() can be called several times on the same promise.
  • .then() should return a new promise.

How to Create ‘Nested’ Node js Promises?

Promises can be nested or chained to one another. This is because when you define a promise, the “then” method itself will return a promise. Take a look at the example here, in which we are nesting to define two callback functions.

// addNumbers function as above


let firstResult = addNumbers(true,10,20)

let secResult = firstResult.then(

function(data) {

// If firstResult was successful, perform add again

return addNumbers(true, data, 20)

},

function(err) {

//If firstResult was unsuccessful, log error

console.error(err)

}

)

secResult.then(addResult, failResult)

//result:

Add result:50

In the above example, The then method itself returns a promise:

This promise here represents the return value for the onResolved or onRejected handlers when they are specified. But since only one of these resolutions is possible, the promise goes for the handler that is called at that point of time.

Since the then method returns a promise, it indicates that the promises can be chained to avoid issues related to the callback:

// addNumbers function as above


addNumbers(true,10,20)
.then((firstResult)=>{

return addNumbers(true,firstResult,20);

})
.then((secResult)=>{

return addNumbers(true,secRes>ult,30);

})
.then(addResult)

.catch(failResult)
.then(()=>{

console.log(“Promise Chaining Ended”)

})

//result

Add result:80

A Next-Gen Node JS App Development Company 

Learn More

Promise Chaining Ended

Note: Above is a clear example of a concept such as “Promise Chaining” or “Promise Sequence”, where things are done in a particular order.

Over to You!

Now that you have a thorough idea about Promise in node js, you can always go for its benefits. INTUZ with its proven track record in building some of the most productive web apps using Node js would appreciate an opportunity to help you achieve your business goal.

INTUZ offers its expertise in varied IT solutions and our team of Node js experts can deliver outstanding results for your business with their in-depth knowledge and experience in building some of the best web apps in business.

Get in touch with us for end-to-end JavaScript development services and hire expert node js developers. Talk to us today!

Full stack development - Guide
Give your enterprise the tech support it deserves.

Let’s Talk

Let us know if there’s an opportunity for us to build something awesome together.

Drop the files
or

Supported format .jpg, .png, .gif, .pdf or .doc

Maximum Upload files size is 4MB