Course

Async/Await

In this lesson, you'll learn about , a modern addition to JavaScript that simplifies working with promises. provides a more intuitive and readable way to handle asynchronous operations, making your code look and behave more like synchronous code.

Async/Await

is a syntactic sugar built on top of promises. It allows you to write asynchronous code that looks and behaves like synchronous code, which makes it easier to read and maintain.

Advantages

  • Readability: Asynchronous functions using resemble synchronous functions, making them easier to understand.
  • Error Handling: You can use blocks to handle errors, similar to synchronous code.

Example

Let's take a look at a simple example:

const fetchNumber = async () => {
    return 25;
}

fetchNumber().then(result => {
    console.log(result); // should log 25
});
  • The function is declared with the keyword, which means it returns a promise.
  • Inside the function, is equivalent to .
  • The method is used to handle the resolved value of the promise.

Await

The keyword is used to pause the execution of an function until a promise is fulfilled. It can only be used inside an function.

  • Non-blocking: Using does not block the entire program; it only pauses the execution of the function until the promise is resolved.

Refactoring with Async/Await

Let's refactor our previous example with callbacks and promises using :

const displayData = async () => {
    try {
        const user = await fetchUser('Adrian');
        const photos = await fetchUserPhotos(user);
        const detail = await fetchPhotoDetails(photos[0]);

        console.log(detail);
    } catch (error) {
        console.error(error);
    }
}
  • The function is declared with the keyword, allowing the use of within it.
  • Each expression pauses the function execution until the promise is resolved, making the code appear synchronous.
  • A block is used to handle any errors that might occur during the asynchronous operations.

Key Takeaways

  • Async/Await: Provides a cleaner and more readable way to work with promises.
  • Await: Pauses the execution of an function until a promise is resolved, without blocking the entire program.
  • Error Handling: Use blocks to handle errors in a manner similar to synchronous code.

By using , you can write asynchronous code that is easier to read and maintain, making it a powerful tool for modern JavaScript development.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Bonus: Understanding the Event Loop