Promise Handling and Async/Await in JavaScript


  In JavaScript, promises are used to handle asynchronous operations. They can be chained using then andcatch, or you can use async/await to write asynchronous code more clearly.


Syntax:


  Promises in JavaScript can be handled in the following ways:

  • then Used to handle the successful outcome of a promise once it has resolved. In the example, after the promise resolves, the result is printed.

  • catch Allows you to handle any error or rejection of a promise. In the second example, the catch method captures the error and displays the error message in the console.

  • async The async keyword is used to declare a function that will implicitly return a promise. In the third example,obtenerDatos is an async function that returns a promise.

  • await Used inside an async function to pause the execution of the asynchronous function until a promise resolves. In the example, the code waits for the promise to resolve before printing the result.

Examples:

then

const promesa = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("¡Promesa resuelta!");
  }, 2000);
});

promesa.then((resultado) => {
  console.log(resultado);  // Output: ¡Promesa resuelta!
});

Explanation:

In this example, the promise resolves after 2 seconds and thethen method handles the promise's result, printing the message to the console.

catch

const promesaRechazada = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("¡Error en la promesa!");
  }, 2000);
});

promesaRechazada.catch((error) => {
  console.log(error);  // Output: ¡Error en la promesa!
});

Explanation:

Here, the promise is rejected after 2 seconds, and thecatch method handles the error, printing the error message to the console.

async/await

async function obtenerDatos() {
  const promesa = new Promise((resolve) => {
    setTimeout(() => {
      resolve("Datos obtenidos");
    }, 2000);
  });

  const resultado = await promesa;
  console.log(resultado);  // Output: Datos obtenidos
}

obtenerDatos();

Explanation:

In this example, the obtenerDatos function is declared as async. Inside it, await is used to wait for the promise to resolve before continuing with the code. The message is printed after 2 seconds.


Purpose:

  • Effectively handle asynchronous operations in JavaScript.
  • Facilitate writing and reading asynchronous code usingasync/await.
  • Resolve promises and handle errors easily with then andcatch.


Exercises



The rest of the content is available only for registered and premium users!



What keyword is used to declare a function that returns a promise?



JavaScript Concepts and Reference

How to use async await with promises in JavaScript? How does async await work in JavaScript? How are promises handled in JavaScript? What is the difference between async and await? Async/await JavaScript Promises JavaScript async/await Async JavaScript JavaScript async/await promises and callbacks Await is only valid in async functions and the top level bodies of modules Async/await C# Js async await promise Async/await then/catch JavaScript