JS Async Patterns

A Deep Dive into Asynchronous JavaScript

Introduction

Asynchronous JavaScript is essential for modern web development, allowing your code to respond to events without blocking the main thread.

It enables you to perform operations in the background, improving user experience and responsiveness.

Key Concepts: Promises, Async/Await, Event Loop

Asynchronous Patterns

Understanding these patterns is crucial for building robust and performant web applications.

Example: Fetch Data

Let's see how to fetch data asynchronously using Promises.

This example fetches a list of users from an API, but in a real application, this would be a real API call.

The code will handle potential errors gracefully.

Promise Example

Another Example: Event Handling

Consider a button click event. Without async/await, you'd need to block the UI thread.

Async/Await allows you to handle the event gracefully without blocking the UI.

``` ```css /* style.css */ body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; } header { background-color: #2981B6; color: #EEEEEE; padding: 20px; text-align: center; border-bottom: 1px solid #E0E0E0; } main { padding: 20px; margin: 20px; background-color: #FFFFFF; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } section { margin-bottom: 20px; padding: 20px; border: 1px solid #EEEEEE; border-radius: 5px; background-color: #F0F0F0; } section h2 { color: #333; } section p { font-size: 16px; line-height: 1.5; } ul { list-style: square; margin-left: 20px; } img { max-width: 100%; height: auto; border-radius: 5px; } footer { background-color: #2981B6; color: #EEEEEE; padding: 20px; text-align: center; font-size: 14px; position: relative; bottom: 0; width: 100%; } ``` ```javascript // js // Example data to fetch (replace with your actual API call) let users = [ { id: 1, name: 'Alice', city: 'New York' }, { id: 2, name: 'Bob', city: 'London' }, { id: 3, name: 'Charlie', city: 'Paris' }, ]; //Async function to fetch data async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } // Call the async function fetchData();