What are Promises in Node.js?


A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap. The Promise is in the Pending state if the operation is still running, Fulfilled if the operation is completed successfully, and Rejected if the operation threw an exception. For more information on Promises and related terminology, see the MDN documentation on promises.

Most driver methods that communicate with your MongoDB cluster, such as findOneAndUpdate() and countDocuments(), return Promise objects and already contain logic to handle the success or failure of the operation.

You can define your own logic that executes once the Promise reaches the Fulfilled or Rejected state by appending the then() method. The first parameter of then() is the method that gets called when the Promise reaches the Fulfilled state and the optional second parameter is the method that gets called when it reaches the Rejected state. The then() method returns a Promise to which you can append additional then() methods.

When you append one or more then() methods to a Promise, each call passes its execution result to the next one. This pattern is called Promise chaining. The following code snippet shows an example of Promise chaining by appending a single then() method.

collection
  .updateOne({ name: "Mount McKinley" }, { $set: { meters: 6190 } })
  .then(
    res => console.log(`Updated ${res.result.n} documents`),
    err => console.error(`Something went wrong: ${err}`),
  );

If you only need to handle Promise transitions to the Rejected state, rather than passing a null first parameter to then(), you can instead use the catch() method which accepts a single callback, executed when the Promise transitions to the Rejected state.

The catch() method is often appended at the end of a Promise chain to handle any exceptions thrown. The following code snippet demonstrates appending a catch() method to the end of a Promise chain.

deleteOne({ name: "Mount Doom" })
  .then(result => {
    if (result.deletedCount !== 1) {
      throw "Could not find Mount Doom!";
    }
    return new Promise((resolve, reject) => {
      ...
    });
  })
  .then(result => console.log(`Vanquished ${result.quantity} Nazgul`))
  .catch(err => console.error(`Fatal error occurred: ${err}`));

Leave a comment

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