Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Master Async/Await for Modern Async Code

- 10.07.26 - ErcanOPAK

⚑ Async/Await = Modern Async

Promises are good. Async/Await is better. Write async code like sync code. Cleaner, more readable.

❌ Promise Chain

fetchUser()
    .then(user => fetchOrders(user))
    .then(orders => fetchDetails(orders))
    .then(details => console.log(details))
    .catch(err => console.error(err));

βœ… Async/Await

try {
    const user = await fetchUser();
    const orders = await fetchOrders(user);
    const details = await fetchDetails(orders);
    console.log(details);
} catch (err) {
    console.error(err);
}

πŸ“ Async/Await Examples

// Basic async function
async function getUserData(userId) {
    const response = await fetch(`/api/users/${userId}`);
    const user = await response.json();
    return user;
}

// Error handling
async function getUserWithErrorHandling(userId) {
    try {
        const user = await fetchUser(userId);
        const orders = await fetchOrders(user.id);
        return { user, orders };
    } catch (error) {
        console.error('Failed:', error);
        throw new Error(`Failed to get user: ${error.message}`);
    }
}

// Parallel execution
async function getUserSummary(userId) {
    const userPromise = fetchUser(userId);
    const ordersPromise = fetchOrders(userId);
    const reviewsPromise = fetchReviews(userId);
    
    const [user, orders, reviews] = await Promise.all([
        userPromise, 
        ordersPromise, 
        reviewsPromise
    ]);
    
    return { user, orders, reviews };
}

// Retry pattern
async function fetchWithRetry(url, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(url);
            if (response.ok) return response.json();
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await delay(1000 * (i + 1));
        }
    }
}

// Timeout pattern
async function fetchWithTimeout(url, timeoutMs = 5000) {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), timeoutMs);
    
    try {
        const response = await fetch(url, { signal: controller.signal });
        clearTimeout(timeout);
        return response.json();
    } catch (error) {
        clearTimeout(timeout);
        throw error;
    }
}

πŸ’‘ Async/Await Tips

  • Always use try-catch
  • Use Promise.all for parallel
  • Avoid blocking with await
  • Use for I/O operations
  • Better than promise chains

“Async/Await makes async code readable. Write sync, run async. Essential for modern JavaScript.”

β€” JavaScript Developer

Related posts:

AJAX β€œStale Data” β€” Browser Caching GET Requests Deeply

How to solve ajax.reload() not working for DataTables in JS File

forEach + async β€” A Hidden Logic Bug

Post Views: 3

Post navigation

HTML: Use IFrames to Embed Content
Ajax: Get Started with GraphQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (597)
  • Add Constraint to SQL Table to ensure email contains @ (582)
  • Average of all values in a column that are not zero in SQL (545)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (512)
  • Find numbers with more than two decimal places in SQL (460)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com