Vai al contenuto
ENCICLOPEDIA.HLP
JavaScriptIntermedio

Async/Await JavaScript

Codice asincrono che si legge come sincrono: gestisci API, database e file senza callback hell.

Async/Await JavaScript

🎯 Cos'è in Parole Semplici?

Il Problema

JavaScript è single-threaded ma deve fare cose che richiedono tempo (API, database, file). Se aspettasse, la pagina si bloccherebbe.

La Soluzione

Async/Await ti permette di scrivere codice che "aspetta" senza bloccare, leggibile come codice normale.

javascript
// 😩 Callback Hell (il passato oscuro)
getUser(id, (user) => {
  getOrders(user.id, (orders) => {
    getProducts(orders[0].id, (products) => {
      // Aiuto...
    });
  });
});

// 😊 Async/Await (il presente luminoso)
const user = await getUser(id);
const orders = await getOrders(user.id);
const products = await getProducts(orders[0].id);

📦 Promises: Le Fondamenta

Una Promise è una "promessa" di un valore futuro.

I 3 Stati

Esempio di codice
┌─────────┐
│ PENDING │  → In attesa di risultato
└────┬────┘
     │
     ├────────┐
     ↓        ↓
┌─────────┐  ┌─────────┐
│FULFILLED│  │REJECTED │
│ (valore) │  │ (errore) │
└─────────┘  └─────────┘

Creare una Promise

javascript
const promessa = new Promise((resolve, reject) => {
  // Simula operazione asincrona
  setTimeout(() => {
    const successo = true;
    
    if (successo) {
      resolve("Dati ricevuti!");  // ✅ Completata
    } else {
      reject(new Error("Fallita"));  // ❌ Errore
    }
  }, 1000);
});

Consumare una Promise

javascript
promessa
  .then(risultato => console.log(risultato))   // Se fulfilled
  .catch(errore => console.error(errore))      // Se rejected
  .finally(() => console.log("Fine"));         // Sempre

✨ Async/Await: La Magia

Sintassi

javascript
// async: "questa funzione ritorna una Promise"
async function fetchData() {
  // await: "aspetta che questa Promise si risolva"
  const response = await fetch('/api/data');
  const data = await response.json();
  return data;
}

Regole

  1. await può essere usato SOLO dentro funzioni async
  2. Una funzione async ritorna SEMPRE una Promise
  3. Se ritorna un valore, è wrapped in Promise.resolve(valore)

⚠️ Error Handling

try/catch (Raccomandato)

javascript
async function fetchUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Fetch fallita:', error);
    throw error;  // Re-throw o gestisci
  }
}

.catch() sulla Promise

javascript
const data = await fetchData().catch(err => {
  console.error(err);
  return null;  // Valore di fallback
});

🚀 Esecuzione Parallela

Promise.all: Tutte devono avere successo

javascript
// ❌ LENTO: Sequenziale (3 secondi totali)
const user = await getUser();     // 1 sec
const posts = await getPosts();   // 1 sec
const comments = await getComments(); // 1 sec

// ✅ VELOCE: Parallelo (1 secondo totale)
const [user, posts, comments] = await Promise.all([
  getUser(),
  getPosts(),
  getComments()
]);

Promise.allSettled: Tutte, anche con errori

javascript
const results = await Promise.allSettled([
  fetch('/api/1'),
  fetch('/api/2'),
  fetch('/api/3')
]);

results.forEach(result => {
  if (result.status === 'fulfilled') {
    console.log('Success:', result.value);
  } else {
    console.log('Error:', result.reason);
  }
});

Promise.race: La prima che finisce

javascript
// Timeout pattern
const result = await Promise.race([
  fetch('/api/data'),
  new Promise((_, reject) => 
    setTimeout(() => reject(new Error('Timeout')), 5000)
  )
]);

Promise.any: La prima che ha SUCCESSO

javascript
// Prova più server, usa il primo che risponde
const data = await Promise.any([
  fetch('https://server1.com/api'),
  fetch('https://server2.com/api'),
  fetch('https://server3.com/api')
]);

📊 Tabella Comparativa

MetodoComportamentoFallisce se...
Promise.allAspetta tutteUNA fallisce
Promise.allSettledAspetta tutteMai (riporta tutti i risultati)
Promise.racePrima che finisceQuella prima fallisce
Promise.anyPrima che ha successoTUTTE falliscono

🔄 Loop e Async

❌ forEach NON funziona con await

javascript
// SBAGLIATO: non aspetta!
ids.forEach(async (id) => {
  await processItem(id);  // Fire and forget!
});
console.log('Fatto');  // Eseguito PRIMA che finisca!

✅ for...of per sequenziale

javascript
for (const id of ids) {
  await processItem(id);  // Uno alla volta
}
console.log('Fatto');  // Dopo TUTTI

✅ Promise.all per parallelo

javascript
await Promise.all(
  ids.map(id => processItem(id))  // Tutti insieme
);
console.log('Fatto');

💡 Pattern Utili

Retry con Backoff Esponenziale

javascript
async function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fetch(url);
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      
      const delay = Math.pow(2, i) * 1000;  // 1s, 2s, 4s
      await new Promise(r => setTimeout(r, delay));
    }
  }
}

Timeout Wrapper

javascript
function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Timeout')), ms)
  );
  return Promise.race([promise, timeout]);
}

const data = await withTimeout(fetch('/api'), 5000);

⚠️ Errori Comuni

  1. Dimenticare await → Ottieni Promise invece del valore
  2. await fuori da async → SyntaxError
  3. forEach con async → Non aspetta
  4. Non gestire errori → Unhandled rejection
  5. Await in sequenza quando puoi parallelizzare → Lento
javascript
// ============================================
// ESEMPI PRATICI ASYNC/AWAIT
// ============================================

// 🌐 1. FETCH API COMPLETA
// ============================================

async function fetchJSON(url, options = {}) {
  const response = await fetch(url, {
    headers: { 'Content-Type': 'application/json' },
    ...options
  });
  
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status}`);
    error.status = response.status;
    error.response = await response.text();
    throw error;
  }
  
  return response.json();
}

// GET
const user = await fetchJSON('/api/users/1');

// POST
const newUser = await fetchJSON('/api/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'Mario', email: 'mario@example.com' })
});


// 🚀 2. FETCH PARALLELO OTTIMIZZATO
// ============================================

async function loadDashboard(userId) {
  // ✅ Tutte partono insieme, aspettiamo tutte
  const [user, posts, notifications, settings] = await Promise.all([
    fetchJSON(`/api/users/${userId}`),
    fetchJSON(`/api/users/${userId}/posts`),
    fetchJSON(`/api/users/${userId}/notifications`),
    fetchJSON(`/api/users/${userId}/settings`)
  ]);
  
  return { user, posts, notifications, settings };
}


// 🔄 3. RETRY CON EXPONENTIAL BACKOFF
// ============================================

async function fetchWithRetry(url, options = {}) {
  const { maxRetries = 3, baseDelay = 1000 } = options;
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url);
      if (response.ok) return response;
      
      // Retry anche su 5xx
      if (response.status < 500) throw new Error(`HTTP ${response.status}`);
      
    } catch (error) {
      const isLastAttempt = attempt === maxRetries - 1;
      
      if (isLastAttempt) {
        throw error;
      }
      
      // Exponential backoff: 1s, 2s, 4s...
      const delay = baseDelay * Math.pow(2, attempt);
      console.log(`⚠️ Tentativo ${attempt + 1} fallito, riprovo in ${delay}ms...`);
      
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}


// ⏱️ 4. TIMEOUT WRAPPER
// ============================================

function withTimeout(promise, ms, errorMessage = 'Timeout') {
  let timeoutId;
  
  const timeout = new Promise((_, reject) => {
    timeoutId = setTimeout(() => {
      reject(new Error(errorMessage));
    }, ms);
  });
  
  return Promise.race([promise, timeout]).finally(() => {
    clearTimeout(timeoutId);
  });
}

// Uso
try {
  const data = await withTimeout(
    fetch('/api/slow-endpoint'),
    5000,
    'La richiesta ha impiegato troppo tempo'
  );
} catch (error) {
  if (error.message.includes('Timeout')) {
    console.log('Timeout! Mostra messaggio all\'utente');
  }
}


// 📊 5. RATE LIMITING / THROTTLE
// ============================================

async function processInBatches(items, batchSize, processFn) {
  const results = [];
  
  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
    
    console.log(`Processing batch ${i / batchSize + 1}...`);
    
    // Processa batch in parallelo
    const batchResults = await Promise.all(
      batch.map(item => processFn(item))
    );
    
    results.push(...batchResults);
    
    // Pausa tra batch per non sovraccaricare
    if (i + batchSize < items.length) {
      await new Promise(r => setTimeout(r, 1000));
    }
  }
  
  return results;
}

// Processa 100 items, 10 alla volta
const results = await processInBatches(
  arrayOf100Items,
  10,
  async (item) => fetchJSON(`/api/process/${item.id}`)
);


// 🛡️ 6. ABORT CONTROLLER (Cancellazione)
// ============================================

function createCancellableFetch(url) {
  const controller = new AbortController();
  
  const promise = fetch(url, { signal: controller.signal })
    .then(res => res.json());
  
  return {
    promise,
    cancel: () => controller.abort()
  };
}

// Uso in React
function useData(url) {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    const { promise, cancel } = createCancellableFetch(url);
    
    promise
      .then(setData)
      .catch(err => {
        if (err.name !== 'AbortError') {
          console.error(err);
        }
      });
    
    return () => cancel();  // Cleanup: cancella se componente smontato
  }, [url]);
  
  return data;
}


// 📝 7. ASYNC QUEUE (Una alla volta)
// ============================================

class AsyncQueue {
  constructor() {
    this.queue = [];
    this.processing = false;
  }
  
  async add(asyncFn) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn: asyncFn, resolve, reject });
      this.process();
    });
  }
  
  async process() {
    if (this.processing || this.queue.length === 0) return;
    
    this.processing = true;
    const { fn, resolve, reject } = this.queue.shift();
    
    try {
      const result = await fn();
      resolve(result);
    } catch (error) {
      reject(error);
    } finally {
      this.processing = false;
      this.process();  // Processa il prossimo
    }
  }
}

const queue = new AsyncQueue();

// Tutte le richieste vengono processate una alla volta
await queue.add(() => fetch('/api/1'));
await queue.add(() => fetch('/api/2'));
await queue.add(() => fetch('/api/3'));
EnciclopediaProgrammazione, dati e intelligenza artificiale