What is Node.js Promise?

What is Node.js Promise?

What is Node.js Promise?

In Node.js, a Promise is an object used to organize and manage asynchronous operations. In JavaScript, a Promise is a structure that represents an asynchronous process that will either be completed or will fail in the future. Promise enables writing more organized and readable code during asynchronous processes and makes it easier to manage complex operations without falling into callback hell.

Promise has a structure with three states:
  • Pending: The promise has not been completed yet and the result is being awaited.
  • Fulfilled: The promise has been completed successfully and a result value is returned.
  • Rejected: The promise has failed and has been rejected due to an error.
The Promise object is created with `new Promise()` and takes two callback functions: `resolve` (to return a result when fulfilled) and `reject` (to return an error when rejected). When the asynchronous operation is complete, the Promise calls the `resolve` function to return the result or, if there is an error, calls the `reject` function to return the error.

An example usage of a Promise:

const myPromise = new Promise((resolve, reject) => {

  // Performing an asynchronous operation

  const isSuccess = true;

  if (isSuccess) {
    // Return result if the operation is successful
    resolve("Successful!");
  } else {
    // Return error if the operation fails
    reject(new Error("The operation failed!"));
  }

});

// Using the Promise object

myPromise
  .then((result) => {
    console.log(result); // "Successful!"
  })
  .catch((error) => {
    console.error(error.message); // "The operation failed!"
  });
  

Promise can also be used with async/await structures, and thus it is possible to write more organized and understandable code.