Junior
Qual è la differenza tra async/await e Promise?
sobes.tech AI
Risposta dell'AI
async/await è uno zucchero sintattico sopra le promesse. Permette di scrivere codice asincrono in modo più leggibile e simile a quello sincrono, usando le parole chiave async per le funzioni che contengono await per attendere la risoluzione di una promessa. Le promesse sono oggetti che rappresentano il completamento (o il fallimento) di un’operazione asincrona e il suo valore risultante.
| Caratteristica | async/await | Promise |
|---|---|---|
| Sintassi | Più simile al codice sincrono. | Usa metodi .then(), .catch(), .finally(). |
| Leggibilità | Generalmente più alta, specialmente nelle catene. | Può portare a "Callback hell" in catene complesse. |
| Gestione errori | Usa try...catch standard. |
Usa .catch() o il secondo argomento in .then(). |
| Parallelismo | Richiede l’uso esplicito di Promise.all() o Promise.allSettled(). |
Può essere più esplicito, ma meno leggibile senza async/await. |
// Esempio con Promise
function getDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Dati ricevuti');
}, 1000);
});
}
getDataPromise()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
// Esempio con async/await
async function getDataAsync() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Dati ricevuti');
}, 1000);
});
}
async function processData() {
try {
const data = await getDataAsync();
console.log(data);
} catch (error) {
console.error(error);
}
}
processData();