Middle
Koja je prednost sintaktičkog šećera predstavljenog u obliku async/await u poređenju sa Promise?
sobes.tech АИ
Одговор од АИ
Glavna prednost async/await u poređenju sa "čistim" promise-ima je mogućnost da pišete asinhroni kod u stilovima koji su bliži sinhronom i čitljivom.
Uporedba:
| Aspekt | Promise |
async/await |
|---|---|---|
| Čitljivost | Može dovesti do "lanaca promise-a". | Omogućava pisanje koda gotovo kao sinhronog. |
| Obrada grešaka | Koristi .catch(). |
Koristi standardni try...catch. |
| Sekvencijalnost | Zahteva pažljivo povezivanje ili Promise.all. |
Jasno i lako za čitanje. |
| Debugging | Može biti teže pratiti tok. | Slično debugovanju sinhronog koda. |
| Sintaksni šum | Mnoge .then(), .catch(). |
Manje boilerplate koda. |
Primer sa promise-ima:
// Primer sa Promise
fetch('user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(githubUser => githubUser.json())
.then(githubUser => {
// Obrada podataka
console.log(githubUser);
})
.catch(error => {
console.error('Greška:', error);
});
Primer sa async/await:
// Primer sa async/await
async function getUserData() {
try {
const userResponse = await fetch('user.json');
const user = await userResponse.json();
const githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
const githubUser = await githubResponse.json();
// Obrada podataka
console.log(githubUser);
} catch (error) {
console.error('Greška:', error);
}
}
getUserData();
Dakle, async/await ne zamenjuje promise-ove, već je to sintaksički šećer iznad njih, koji čini asinhrone operacije intuitivnijim i lakšim za održavanje.