Chuck's Academy

Intermediate JavaScript

Advanced Promises and Async/Await

Handling asynchrony in JavaScript is fundamental for working with operations that take time to complete, such as API requests or file processing. In this chapter, we will explore advanced techniques for handling Promises and the use of async and await.

![promise en javascript(/uploads/promise_2ad629aaf8.jpg)

Creating Promises

A Promise represents an asynchronous operation that can either be completed (resolve) or fail (reject).

javascript
"Here, we create a Promise that completes successfully if 'success' is true, calling 'resolve'. If it is false, 'reject' is called."

Promise Chaining

Promises can be chained using then to handle results and catch to handle errors.

javascript
"In this example, we chain 'then' to transform the result to uppercase, and use 'catch' at the end to capture errors if they occur."

async and await

async and await are keywords that allow working with Promises in a more readable way, as if they were synchronous functions.

javascript
"Here, 'fetchData' is an asynchronous function that waits for the 'fetch' response and then converts that response to JSON. If an error occurs, it is captured in the 'catch' block."

Error Handling with try/catch

Using try/catch in asynchronous functions allows capturing errors similarly to synchronous programming.

javascript
"In this example, we use 'try/catch' to capture errors in the asynchronous function 'getUserData' when 'fetchUser' fails."

Parallel Execution with Promise.all

Promise.all allows executing multiple Promises in parallel and waiting for all of them to complete before proceeding.

javascript
"We use 'Promise.all' to execute requests for 'posts' and 'comments' in parallel and wait for both to complete before processing the data."

Promise.race for Promise Competition

Promise.race allows executing multiple Promises and only returns the result of the first Promise that resolves or rejects.

javascript
"Here, 'Promise.race' executes a request to the API and a timer. If the request takes more than 5 seconds, the timer rejects the Promise with 'Timed out'."

Delays with setTimeout in Promises

Sometimes, it is useful to delay a Promise for a specific time. We can combine setTimeout with Promises to create a delay.

javascript
"In this example, 'delay' is a function that returns a Promise resolved after a specific time. 'delayedMessage' displays an initial message, waits 2 seconds, and then displays another message."

Conclusion

cuadro comparativo entre promesas y async/awaitcuadro comparativo entre promesas y async/await

Advanced handling of Promises and the use of async/await in JavaScript allow you to work with asynchrony in a clear and efficient way. With techniques like Promise.all and Promise.race, you can execute multiple asynchronous operations and manage response times effectively.


Ask me anything