1. Overview

As we have seen in callback concepts, sometimes callback functions become a nightmare when it comes to nested callbacks(callback hell). In this article, we will learn the basics of Promise in the Nodejs, what they are, how to create them, how to use them, and what are the drawbacks of promise in Nodejs.

2. Nodejs Promise

2.1 Why Promise?

  • To handle asynchronous operations in the simplest manner.

2.2 What is a Promise?

As per the official documentation,

A Promise in Nodejs is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

2.2.1 States of promise

  • pending: the initial state of promise, neither fulfilled nor rejected.
  • fulfilled: a state which represents, the operation completed successfully.
  • rejected: a state which represents, the operation failed.

2.3 Creating a promise in Nodejs

The simplest way to create a promise,

var myPromise = new Promise(function(resolve, reject) {
    //Do something 
});
myPromise.then(data => {
   //Process data
}).catch(err => {
   //Error handling
});

Code within function performs some tasks return meaningful return value(promiseObject). The myPromise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. The object returned by promise invokes .then() associated with it. If promise get rejected, it handles by .catch() block. Otherwise, you can process data returned by promise inside .then() block.

3. Examples of Nodejs Promise

3.1 Promise Resolution

With valid JSON string,

function parseJsonString(jsonStr) {
    return new Promise((resolve, reject) => {
        try {
            let obj = JSON.parse(jsonStr);
            resolve(obj);
        } catch (err) {
            reject(err);
        };
    });
}
let myPromise = parseJsonString('{"name":"John", "age":30}');
myPromise.then(data => {
    console.log("Parsed data :", data);
}).catch(err => {
    console.log(err);
});

Output:

3.2 Promise rejection

let’s pass erroneous JSON string, as per our assumption it should throw an error, right? Consider the below example, It will throw an error. So, it goes in rejection state throw catch block and will be caught by catch block of .then().

function parseJsonString(jsonStr) {
    return new Promise((resolve, reject) => {
        try {
            let obj = JSON.parse(jsonStr);
            resolve(obj);
        } catch (err) {
            reject(err);
        };
    });
}
let myPromise = parseJsonString('{"lang":"Java" "name":"Developer zone"}');
myPromise.then(data => {
    console.log("Parsed data :", data);
}).catch(err => {
    console.log("Rejected :", err);
});

Output:

4. Chained/Nested Promise in Nodejs

When your method has 2 or more than 2 tasks and you want to perform these tasks one after another, in this scenario chained or nested Promise can be used.

const myPromise =
  (new Promise(task1))
  .then(resolvedTask1)
  .then(resolvedTask2)
  ...
  .catch(handleRejectedAny);

function inside .then() returns promise object and handles rejection if any.

5. Promise.all() in Nodejs

Promise.all() returns single a promise when all promise passed as an iterable has been fulfilled. Iterable can contain promise/non-promise. Unlike nested promise, it can be used when a method needs to run multiple asynchronous tasks parallelly.

const myPromise1 = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve(200);
    }, 3000);
});
const myPromise2 = Promise.resolve("Java developer zone");
const myPromise3 = 400;

Promise.all([myPromise1, myPromise2, myPromise3]).then(function(values) {
    console.log(values);
});

Output:

6. Drawbacks

  • In chained promise, if an error occurred error stack returned from chain doesn’t give clue where an error has occurred.
  • Lines of code are more compare to async/await.
  • Not possible to handle synchronous and asynchronous errors with the same try/catch block.

7. Conclusion

Though, everything has its pros and cons. So, where to use? Well, it depends on use-cases, your knowledge of particular concepts and thumb rules. What we learned about the promise of Nodejs in this blog is what is a promise and how to create a promise. We have learned other concepts like a nested or chained promise in Nodejs, different states of promise, Promise.all(), and drawbacks of promise.

8. References

 

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *