Sobes.tech
Middle

Async/await şeklinde sunulan sözdizimi şekerinin Promise ile karşılaştırıldığında avantajı nedir?

sobes.tech yapay zeka

AI'dan gelen yanıt

Async/await'in "temiz" promise'lara göre en büyük avantajı, asenkron kodu daha senkron ve okunabilir bir tarzda yazma imkanı sağlamasıdır.

Karşılaştırma:

Açıkla Promise async/await
Okunabilirlik "Promise zincirleri"ne yol açabilir. Neredeyse senkron gibi kod yazmaya olanak tanır.
Hata işleme .catch() kullanır. Standart try...catch kullanır.
Sıralılık Dikkatli zincirleme veya Promise.all gerektirir. Açık ve kolay okunur.
Hata ayıklama Takip etmek daha zor olabilir. Senkron kod hata ayıklamasına yakın.
Söz dizimi gürültüsü Çok sayıda .then(), .catch(). Daha az boilerplate kodu.

Promise'lar ile örnek:

// Promise ile örnek
fetch('user.json')
  .then(response => response.json())
  .then(user => fetch(`https://api.github.com/users/${user.name}`))
  .then(githubUser => githubUser.json())
  .then(githubUser => {
    // Veri işleme
    console.log(githubUser);
  })
  .catch(error => {
    console.error('Hata:', error);
  });

Async/await ile örnek:

// Async/await ile örnek
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();

    // Veri işleme
    console.log(githubUser);
  } catch (error) {
    console.error('Hata:', error);
  }
}

getUserData();

Bu nedenle, async/await promise'ları değiştirmez, onların üzerinde sözdizimi şekeridir ve asenkron işlemleri daha sezgisel ve bakımı kolay hale getirir.