Sobes.tech
Middle

È possibile concatenare un .then() a un .catch()?

sobes.tech AI

Risposta dell'AI

Sì, è possibile concatenare .then() a .catch(). Nelle promesse JavaScript, la catena di metodi .then() e .catch() restituisce una nuova promessa, quindi è possibile costruire chiamate sequenziali.

Ad esempio:

fetch('/api/data')
  .then(response => response.json())
  .catch(error => {
    console.error('Errore:', error);
    return { fallback: true };
  })
  .then(data => {
    console.log('Dati:', data);
  });

In questo esempio, se si verifica un errore, verrà gestito in .catch(), e il successivo .then() verrà eseguito con il risultato di .catch(). Questo è utile per gestire gli errori e continuare la catena con dati alternativi.