J

Async/Await & Promises

JavaScript Syntax Guide

Asynchrone Programmierung mit Promises und async/await

Async/Await & Promises

Asynchrone Programmierung mit Promises und async/await

JavaScript async/await & promises (javascript)
        
          // 1. UNDERSTANDING CALLBACK HELL (The Problem)
setTimeout(() => {
  console.log('Step 1');
  setTimeout(() => {
    console.log('Step 2');
    setTimeout(() => {
      console.log('Step 3');
      // This nesting becomes unmanageable!
    }, 1000);
  }, 1000);
}, 1000);

// 2. PROMISES (The Solution)
const fetchUser = (id) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 1) {
        resolve({ id: 1, name: 'John', email: 'john@example.com' });
      } else if (id === 2) {
        resolve({ id: 2, name: 'Jane', email: 'jane@example.com' });
      } else {
        reject(new Error(`User with id ${id} not found`));
      }
    }, 1000);
  });
};

// 3. PROMISE CHAINING (.then/.catch)
fetchUser(1)
  .then(user => {
    console.log('User found:', user);
    return user.email; // Return value for next .then
  })
  .then(email => {
    console.log('Sending email to:', email);
    return `Email sent to ${email}`;
  })
  .then(result => {
    console.log('Result:', result);
  })
  .catch(error => {
    console.error('Error occurred:', error.message);
  })
  .finally(() => {
    console.log('Operation completed (success or failure)');
  });

// 4. ASYNC/AWAIT (Syntactic Sugar)
async function getUserData(id) {
  try {
    const user = await fetchUser(id);
    console.log('User:', user);

    // Simulate another async operation
    const profile = await fetchUserProfile(user.id);
    console.log('Profile:', profile);

    return { user, profile };
  } catch (error) {
    console.error('Failed to get user data:', error.message);
    throw error; // Re-throw to caller
  }
}

// Usage
getUserData(1)
  .then(data => console.log('All data:', data))
  .catch(err => console.error('Operation failed:', err));

// 5. CONCURRENT OPERATIONS
// Promise.all - All must succeed
const userIds = [1, 2];
const userPromises = userIds.map(id => fetchUser(id));

Promise.all(userPromises)
  .then(users => {
    console.log('All users loaded:', users);
  })
  .catch(error => {
    console.log('One request failed:', error.message);
    // If any promise rejects, Promise.all rejects immediately
  });

// Promise.allSettled - Get results regardless of success/failure
Promise.allSettled(userPromises)
  .then(results => {
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        console.log(`User ${userIds[index]}: `, result.value);
      } else {
        console.log(`User ${userIds[index]} failed: `, result.reason.message);
      }
    });
  });

// Promise.race - First to complete wins
Promise.race(userPromises)
  .then(winner => console.log('First result:', winner))
  .catch(error => console.log('First error:', error));

// 6. ERROR HANDLING PATTERNS
async function safeApiCall(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    return await response.json();
  } catch (error) {
    if (error.name === 'TypeError') {
      console.error('Network error:', error.message);
    } else if (error.message.includes('HTTP')) {
      console.error('Server error:', error.message);
    } else {
      console.error('Unknown error:', error.message);
    }
    throw error; // Re-throw for caller to handle
  }
}

// 7. ASYNC UTILITY FUNCTIONS
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function retryOperation(operation, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      console.log(`Attempt ${i + 1} failed, retrying...`);
      await delay(1000 * (i + 1)); // Exponential backoff
    }
  }
}

// Usage with retry
const unreliableApiCall = () => fetchUser(Math.random() > 0.7 ? 1 : 999);
retryOperation(unreliableApiCall)
  .then(result => console.log('Success:', result))
  .catch(err => console.log('All retries failed:', err.message));

// 8. ASYNC ITERATORS & GENERATORS (Advanced)
async function* asyncGenerator() {
  const users = [1, 2, 3];
  for (const id of users) {
    yield await fetchUser(id);
  }
}

// Usage
(async () => {
  for await (const user of asyncGenerator()) {
    console.log('Generated user:', user);
  }
})();
        
      

Explanation

JavaScript behandelt asynchrone Operationen mit Promises und async/await. Promises repräsentieren die eventuelle Vollendung asynchroner Operationen, während async/await synchron-aussehende Syntax bereitstellt.

Common Use Cases

  • API-Aufrufe
  • Dateioperationen
  • Datenbankabfragen
  • Timer-basierte Operationen

Related JavaScript Syntax

Master Async/Await & Promises in JavaScript

Understanding Async/Await & Promises is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Async/Await & Promises effectively in your JavaScript projects.

Key Takeaways

  • API-Aufrufe
  • Dateioperationen
  • Datenbankabfragen