Gestione errori async in JavaScript
Livello 5676 battiture
Questo implementa la logica di retry con async/await per gestire errori temporanei.
Codice JavaScript
// Fetch con retry automatico in caso di fallimento1async function fetchWithRetry(url, retries = 3) { // Prova fino a 'retries' volte2 for (let i = 0; i < retries; i++) {3 try {4 console.log(`Attempt ${i + 1}...`); // Attende fakeFetch; se viene rifiutata, l'esecuzione passa al catch5 const response = await fakeFetch(url); // Successo - restituisce immediatamente6 return response;7 } catch (error) {8 console.log(`Failed: ${error.message}`); // Se questo era l'ultimo tentativo, lancia l'errore9 if (i === retries - 1) throw error; // Aspetta prima di riprovare (backoff esponenziale possibile)10 await delay(1000);11 }12 }13}14 // Helper di delay semplice15function delay(ms) {16 return new Promise(r => setTimeout(r, ms));17}18 // Simula un'API che fallisce e ha successo al 3° tentativo19let attempts = 0;20function fakeFetch(url) {21 return new Promise((resolve, reject) => {22 attempts++; // Fallisce i primi 2 tentativi, successo al 3°23 if (attempts < 3) reject(new Error("Network error"));24 else resolve({ data: "Success!" });25 });26}27 // Chiama la funzione di retry; then stampa il risultato, catch l'errore finale28fetchWithRetry("api/data")29 .then(data => console.log(data))30 .catch(err => console.log("Final error:", err));Output
Attempt 1...
Failed: Network error
Attempt 2...
Failed: Network error
Attempt 3...
{ data: 'Success!' }Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice JavaScript e quante volte compaiono.
(× 23)× 23;× 15=× 11.× 10{× 10}× 10"× 8+× 5,× 4