Junior
Qual è la differenza tra l'utilizzo di Promise e la sintassi async/await?
sobes.tech AI
Risposta dell'AI
Promise rappresenta un oggetto che riflette il completamento o il rifiuto di un'operazione asincrona. Gestisce i flussi asincroni tramite callback .then() e .catch().
async/await è uno zucchero sintattico su Promise, che rende il codice asincrono più leggibile e simile a quello sincrono. Una funzione contrassegnata come async restituisce sempre una Promise. L'operatore await può essere usato solo all'interno di funzioni async e sospende l'esecuzione della funzione finché la Promise non viene risolta o rifiutata, restituendo il suo risultato o generando un'eccezione.
| Aspetto | Promise | Async/Await |
|---|---|---|
| Leggibilità | Richiede catene .then() e .catch() |
Sembrante al codice sincrono, flusso lineare |
| Gestione degli errori | Usa .catch() |
Usa blocchi try...catch |
| Flusso di esecuzione | Gestito da callback | Sospende/riprende la funzione |
| Valore restituito | Promise | Promise (per funzioni async) o risultato di Promise (per await) |
| Dipendenza | Meccanismo autonomo | Basato su Promise |
Esempio con Promise:
// Esempio con Promise
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Dati ricevuti (Promise)");
}, 1000);
});
}
fetchDataPromise()
.then(data => console.log(data))
.catch(error => console.error(error));
Esempio con async/await:
// Esempio con async/await
function fetchDataAsync() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Dati ricevuti (async/await)");
}, 1000);
});
}
async function showData() {
try {
const data = await fetchDataAsync();
console.log(data);
} catch (error) {
console.error(error);
}
}
showData();