Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Promises | Asynchronous JavaScript and APIs
Advanced JavaScript Mastery
course content

Contenido del Curso

Advanced JavaScript Mastery

Advanced JavaScript Mastery

1. Classes
2. DOM Manipulation
3. Events and Event Handling
4. Asynchronous JavaScript and APIs

bookPromises

What is a Promise?

A Promise is a placeholder for a future value, which could be:

Promises help streamline the handling of asynchronous code by allowing you to attach callbacks that execute when the operation succeeds or fails.

Understanding resolve, reject, and then() Methods

Creating a Promise

To create a Promise, you pass a function with two parameters: resolve and reject. These parameters are functions used to indicate whether the asynchronous operation has been completed successfully or has failed.

  • resolve(value): Marks the Promise as fulfilled (successful) and passes the result (value);
  • reject(error): Marks the Promise as rejected (failed) and passes the error.

Using then() to Handle Resolved Promises:

Once a Promise is created, you can handle the result using the then() method. This method is called when the Promise is fulfilled (resolved).

In this example, the then() method receives the value passed to resolve() and executes the callback with the result. It runs only if the Promise is resolved successfully.

Error Handling with .catch()

Promises provide a simple way to handle errors through the .catch() method. If a Promise is rejected (fails), the error is caught and handled inside .catch().

1234567891011121314151617
const myPromise = new Promise((resolve, reject) => { const success = false; // Simulate a failure if (success) { resolve('Task completed successfully!'); } else { reject('Task failed.'); } }); myPromise .then(result => { console.log(result); }) .catch(error => { console.error('Error:', error); // Output: Error: Task failed. });
copy

catch() method is used to handle errors when the Promise is rejected. It catches the error passed by reject() and allows you to manage failure scenarios.

Chaining Promises for Sequential Asynchronous Operations

One of the key benefits of Promises is the ability to chain them together, allowing you to handle multiple asynchronous operations in sequence without falling into callback hell. Each then() returns a new Promise, enabling you to chain multiple then() calls in a sequence, with the results displayed in the HTML as each Promise resolves.

html

index

css

index

js

index

copy

Sequential Operations: Each then() returns a new Promise, passing the result from one operation to the next. This allows for a clean, linear sequence of asynchronous operations that updates the displayed text in HTML.

Error Handling: The .catch() method handles any error that occurs during any of the Promise resolutions. This ensures that errors are caught and displayed on the page, no matter where they occur in the chain.

Why Use Promises?

  1. Avoiding Callback Hell: Promises offer a cleaner and more readable way to handle asynchronous operations than deeply nested callbacks;
  2. Error Handling: Promises provide built-in error handling with .catch(), making it easy to handle rejected operations;
  3. Sequential Chaining: Promises allow you to run multiple asynchronous operations in sequence using chaining, making code easier to follow and maintain.
1. What is a Promise?
2. In the following code, what will `.catch()` do if there’s an error in one of the `.then()` callbacks?
What is a Promise?

What is a Promise?

Selecciona la respuesta correcta

In the following code, what will `.catch()` do if there’s an error in one of the `.then()` callbacks?

In the following code, what will .catch() do if there’s an error in one of the .then() callbacks?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt