Promises in JavaScript: An Introduction

If you've ever worked with asynchronous operations in JavaScript, you may have come across the concept of promises. Promises provide a way to handle asynchronous operations in a more elegant and manageable way. In this blog post, we'll go over the basics of promises and provide examples of how they can be used.

What is a Promise?

A promise is an object that represents a value that may not be available yet, but will be resolved in the future. Promises are used to handle asynchronous operations, such as API requests, database queries, and other long-running tasks. The three states of a promise are:

  1. Pending: The initial state of the promise before it's resolved or rejected.

  2. Resolved: The state of the promise when it's successfully resolved with a value.

  3. Rejected: The state of the promise when it's unable to be resolved with a value.

Promises provide a way to handle asynchronous operations that are dependent on each other. For example, if you need to make an API request to retrieve some data, and then use that data to make another API request, you can use promises to ensure that the second request waits for the first request to complete before executing.

Creating a Promise

Promises are created using the Promise constructor. The Promise constructor takes a single argument, a function, that is called immediately when the promise is created. The function takes two arguments: a resolve function and a reject function.

Here's an example of creating a promise that resolves after a set amount of time:

javascriptCopy codeconst myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise resolved!');
  }, 1000);
});

In this example, the promise is created and then immediately sets a timeout for 1 second. When the timeout completes, the promise is resolved with the value "Promise resolved!".

Using a Promise

Once a promise is created, it can be used to handle the asynchronous operation. Promises provide a then() method that is called when the promise is successfully resolved and a catch() method that is called when the promise is rejected. The then() method takes a callback function as an argument that is executed when the promise is resolved, and the catch() method takes a callback function as an argument that is executed when the promise is rejected.

Here's an example of using the promise we created earlier:

javascriptCopy codemyPromise.then((result) => {
  console.log(result);
}).catch((error) => {
  console.error(error);
});

In this example, the then() method takes a callback function that logs the result of the promise to the console. The catch() method takes a callback function that logs any errors that occur.

Chaining Promises

Promises can also be chained together to handle multiple asynchronous operations that depend on each other. This is done using the then() method, which returns a new promise. The new promise is resolved with the value returned by the callback function of the then() method.

Here's an example of chaining promises together:

javascriptCopy codeconst firstPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('First Promise resolved!');
  }, 1000);
});

const secondPromise = firstPromise.then((result) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${result} Second Promise resolved!`);
    }, 1000);
  });
});

secondPromise.then((result) => {
  console.log(result);
}).catch((error) => {
  console.error(error);
});

In this example, we create two promises. The first promise is resolved after 1 second with the value "First Promise resolved!". The second promise is chained to the first promise

Happy Learning :)

ย