Promises in javascript simply explained
Tags: javascript, webdev, programming
Published: 2022-12-25 21:21:26

JavaScript promises are a way to handle asynchronous code in a more organized and predictable way. They allow you to write code that is executed after a certain action has been completed, without blocking the rest of the code from running.

Imagine that you are at a restaurant and you order a meal. You are hungry and want to eat your meal as soon as possible, but the chef has to cook it first. While you are waiting for your meal to be ready, you might do other things, such as chatting with your friends or checking your phone.

In this analogy, the process of cooking your meal is like an asynchronous action. It takes some time to complete, and you can't control when it will be done. However, you can still do other things while you are waiting.

Promises are like a promise from the chef to let you know when your meal is ready. When you order your meal, the chef might say "I promise to let you know when your meal is ready." This is like creating a promise in JavaScript.

Here is an example of how you might use a promise in JavaScript to handle an asynchronous action:

```
function orderMeal() {
  return new Promise((resolve, reject) => {
    // simulate the process of cooking a meal
    setTimeout(() => {
      const meal = {
        name: "Spaghetti Bolognese",
        temperature: "hot",
        served: true
      };
      resolve(meal); // the meal is ready, so resolve the promise
    }, 2000); // it takes 2 seconds to cook the meal
  });
}

// order the meal and wait for it to be ready
orderMeal()
  .then(meal => {
    console.log(`Your ${meal.name} is ready! It is ${meal.temperature} and it has been served.`);
  })
  .catch(error => {
    console.error(error);
  });
```
In this example, the orderMeal function returns a promise that is resolved when the meal is ready. The then method is used to specify a callback function that is executed when the promise is resolved, and the catch method is used to handle any errors that might occur.

Here is another example using promises to fetch data from an api since that where promises are mostly applied

```
function getUser() {
  return new Promise((resolve, reject) => {
    // make an HTTP request to a server to get the user's information
    fetch("https://my-api.com/users/123")
      .then(response => response.json())
      .then(data => {
        const user = {
          id: data.id,
          name: data.name,
          email: data.email
        };
        resolve(user); // the user data has been retrieved, so resolve the promise
      })
      .catch(error => {
        reject(error); // there was an error, so reject the promise
      });
  });
}

// get the user's information and wait for it to be retrieved
getUser()
  .then(user => {
    console.log(`Hello, ${user.name}! Your email is ${user.email}.`);
  })
  .catch(error => {
    console.error(error);
  });

```
In this example, the getUser function returns a promise that is resolved when the user's information has been retrieved from the server. The then method is used to specify a callback function that is executed when the promise is resolved, and the catch method is used to handle any errors that might occur.
hope you enjoyed reading ! happy coding