JavaScript Promise

A JavaScript Promise is an object that represents the eventual completion or failure of an asynchronous operation. It lets you associate handlers with the potential success value or reason for failure of an asynchronous operation. This lets asynchronous methods return values like synchronous methods: instead of immediately giving back the final output, the asynchronous method returns a promise to supply the value at some point in the future.

Promise States

A Promise can be in one of three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation was completed successfully.
  • Rejected: The operation failed.

Promise Methods

There are a few methods that you can use to interact with Promises:

  • then(): This method is used to attach a handler to the Promise’s fulfillment or rejection.
  • catch(): This method is used to attach a handler to the Promise’s rejection.
  • finally(): This method is used to attach a handler that will be called regardless of whether the Promise is fulfilled or rejected.

Promise Chaining

You can chain Promises together using the then() method. This allows you to chain together multiple asynchronous operations and handle the results of each operation in a single place.

For example, the following code chains together two Promises:

let promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('Hello, world!');
  }, 1000);
});

let promise2 = promise1.then(function(value) {
  console.log(value);
  return 'Goodbye, world!';
});

promise2.then(function(value) {
  console.log(value);
});

This code will first wait 1 second for the first Promise to resolve. Once the first Promise resolves, the then() method will be called with the value of the first Promise as its argument. The then() method will then return a new Promise that will be resolved with the value of the second Promise.

Promise Rejection

If an asynchronous operation fails, the Promise will be rejected. The catch() method can be used to handle the rejection of a Promise.

For example, the following code shows how to handle the rejection of a Promise:

let promise = new Promise(function(resolve, reject) {
  try {
    // Do something that might fail.
  } catch(error) {
    reject(error);
  }
});

promise.catch(function(error) {
  console.log(error);
});

This code will first try to do something that might fail. If the operation fails, the catch() method will be called with the error as its argument.

Conclusion

Promises are a powerful tool for handling asynchronous operations in JavaScript. They allow you to write code that is more concise, easier to read, and easier to debug.

If you are new to Promises, I recommend checking out the following resources:

  • MDN Web Docs: Promise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise