DEV Community

João Paulo
João Paulo

Posted on

A little about promises in Javascript

JavaScript is a synchronous programming language; however, due to the callback functions, we can make it work as an asynchronous programming language.

The concept of promises are very similar to promises we make in real life, we guarantee that something will be done. A promise can be kept or broken and you hope to know what the promise ended up being.

In terms of code, this is precisely what occurs. Promises can assume the statuses of pending, resolved, or rejected.

The promise object possesses both prototype methods and static methods. The prototypes are those that can only be applied to instances of the promise class. There are three prototypes: then, catch, finally. They all return a promise and handle the states of onFulfilled, onRejected, onFinally, respectively.

There are 4 static methods: reject and resolve, which help you create resolved or rejected promises and all and race. “all” receives an array of promises and returns a promise that resolves when all past promises are resolved or a promise that rejects with the reason for the first promise that was rejected. “race” also receives an array of promises and returns a promise that is resolved or rejected as soon as one of the passed promises is resolved or rejected. All promises run in parallel. This is an interesting feature that allows you to improve the performance of your code.

In modern JavaScript code, you will see a lot of use of async and await, which were introduced to simplify promise management with much more readable code. Async declares a function as asynchronous and await waits for promises to be resolved, pausing execution until the promise is resolved or rejected. This new nomenclature is more modern and avoids the famous “callback hell” (deep nesting of callbacks) of javascript.

Callback hell Example:

function main() {
  getUserData(1, (err, userData) => {
    if (err) {
      console.error(err);
      return;
    }
    getUserOrders(userData.userId, (err, orders) => {
      if (err) {
        console.error(err);
        return;
      }
      getOrderProducts(orders[0].orderId, (err, products) => {
        if (err) {
          console.error(err);
          return;
        }
        processProducts(products, (err, result) => {
          if (err) {
            console.error(err);
            return;
          }
          console.log(result);
        });
      });
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

async/await

async function main() {
  try {
    const userData = await getUserData(1);
    const orders = await getUserOrders(userData.userId);
    const products = await getOrderProducts(orders[0].orderId);
    const result = await processProducts(products);
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

In summary, Promises are a powerful tool in JavaScript for handling asynchronous operations, providing a clear and structured way to manage the flow of asynchronous code execution. With the introduction of async/await, promise management has become even more intuitive, allowing developers to write asynchronous code that resembles synchronous code in terms of readability and maintainability. Understanding and using promises effectively is essential for developing modern and efficient JavaScript applications.

Thank you for reaching this point. If you need to contact me, here is my email: joaopauloj405@gmail.com

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay