The Difference Between Promise And Async/Await In Node.js

·

4 min read

There are different ways to handle operations in NodeJS or JavaScript. For asynchronous execution, different processes run simultaneously and are handled once the result of each process is available. There are different ways to handle the asynchronous code in NodeJS or in JavaScript which are:

1. Promises:

A Promise in NodeJS is similar to a promise in real life. It is an assurance that something will be done. Promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred. It is an object having 3 states namely:

  • Pending: Initial State, before the event has happened.

  • Resolved: After the operation completed successfully.

  • Rejected: If the operation had error during execution, the promise fails.

Example: While requesting data from a database server, the Promise is in a pending state until the data is received. If the data is received successfully, then the Promise is in resolved state and if the data could not be received successfully, the Promise is in the rejected state.

Error Handling of Promises: For a successfully resolved promise, we use .then() method and for rejected promise, we use .catch() method. To run a code after the promise has been handled using .then() or .catch() method, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise.

Example:

 const promise = new Promise(function (resolve, reject) {
    const string1 = "geeksforgeeks";
    const string2 = "geeksforgeeks";
    if (string1 === string2) {
      resolve();
    } else {
      reject();
    }
  });

  promise
    .then(function () {
      console.log("Promise resolved successfully");
    })
    .catch(function () {
      console.log("Promise is rejected");
    });

Output:

Promise resolved successfully

2. Async/Await:

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

await can only be used in async functions. It is used for calling an async function and waits for it to resolve or reject. await blocks the execution of the code within the async function in which it is located.

Error Handling in Async/Await: For a successfully resolved promise, we use try and for rejected promise, we use catch. To run a code after the promise has been handled using try or catch, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise.

Example:

const helperPromise = function () {
    const promise = new Promise(function (resolve, reject) {
    const x = "geeksforgeeks";
    const y = "geeksforgeeks";
    if (x === y) {
        resolve("Strings are same");
    } else {
        reject("Strings are not same");
    }
    });

    return promise;
};

async function demoPromise() {
    try {
    let message = await helperPromise();
    console.log(message);
    } catch (error) {
    console.log("Error: " + error);
    }
}

demoPromise();

Output:

Strings are same

Difference Between Promise and Async/Await:

Sr.no

Promise

Async/Await

1.

Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future.

Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously.

2.

Promise has 3 states – resolved, rejected and pending.

It does not have any states. It returns a promise either resolved or rejected.

3.

If the function “fxn1” is to executed after the promise, then promise.then(fxn1) continues execution of the current function after adding the fxn1 call to the callback chain.

If the function “fxn1” is to executed after await, then await X() suspends execution of the current function and then fxn1 is executed.                                

4.

Error handling is done using .then() and .catch() methods.

Error handling is done using .try() and .catch() methods.

5.

Promise chains can become difficult to understand sometimes.

Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.