Conteúdo do Curso
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Async/Await
The async/await syntax is a modern and more readable way to work with promises in JavaScript. It allows developers to write asynchronous code that looks and behaves like synchronous code. Instead of chaining then()
calls, you can use await
to pause the execution of an async
function until a promise is resolved.
How async Functions Work
An async
function is a function declared with the async
keyword. It returns a Promise by default, and you can use the await
keyword within it to pause execution until the promise is resolved.
index
index
index
The fetchData
function is declared as async
, allowing it to use await
to pause execution until a promise resolves. Here, a simulated delay of 2 seconds mimics a data-fetching operation. Once resolved, the result ("Data fetched successfully!") is displayed in the HTML paragraph.
Simplifying Promise Chains with Async/Await
When working with multiple asynchronous operations in sequence, using async/await
can simplify code that would otherwise involve promise chaining with then()
.
Let's see how a series of promises (like fetching and processing data) can be handled more cleanly with async/await
.
index
index
index
The processData
function calls three asynchronous functions—fetchData
, processFetchedData
, and displayProcessedData
—one after the other, each waiting (await
) for the previous operation to complete before moving to the next. This structured flow eliminates the need for chaining promises, improving readability. The final output ("Raw Data processed and displayed on the page") is then shown in the HTML.
Error Handling with try...catch in Async/Await
Handling errors in promise chains with .catch()
can become cumbersome, especially when dealing with multiple asynchronous operations. With async/await
, you can handle errors using the traditional try...catch
block, making error handling more intuitive and readable.
index
index
index
In fetchDataWithError
, the try
block runs the await
operation, and if it succeeds, the result is displayed in the HTML. If an error occurs (as simulated by simulateError
), the catch
block handles it by setting the paragraph text to the error message ("Error: Something went wrong!").
Obrigado pelo seu feedback!