API'den görsel listesi çekme
async/await ile bir API'den görsel listesini çekip json olarak alırsın.
async/await ile fetch
Bir async fonksiyon içinde await ile fetch çağrısını bekletiriz. fetch(url) bir Response nesnesi döndürür; başarılıysa response.ok true olur.
Akış şöyledir:
const response = await fetch(url)ile isteği bekletif (!response.ok)ile hata denetleawait response.text()ile gövdeyi al
Bu deseni fetchImages adında bir fonksiyonda toplayacağız.
try/catch ile hata yakalama
Ağ istekleri çeşitli nedenlerle başarısız olabilir: yanlış adres, bağlantı kopması veya sunucu hatası. try bloğu içine alınmış await çağrısı bir hata fırlatırsa, denetim catch bloğuna geçer.
Örneğin:
try {
const response = await fetch(url);
} catch (error) {
console.log(error.message);
}Böylece uygulama çökmeden hatayı yakalarız.
Uygulama fetchImages fonksiyonunu yaz
Önceki dersin çözümünün üzerine devam et. url parametresi alan fetchImages adında bir async fonksiyon yaz. try bloğunda const response = await fetch(url) ile yanıtı al; if (!response.ok) ise throw new Error('HTTP ' + response.status) fırlat. Sonra return await response.text() ile gövdeyi döndür. catch (error) bloğunda console.log(error.message) ile hatayı yazdır.
Örnek çözümü göster
async function fetchImages(url) ile başla, try bloğunda fetch ve response.ok denetimini yap, return await response.text() ile döndür, catch (error) ile hatayı console.log ile yazdır.
Örnek çözüm:
// Galeri uygulaması
const app = document.getElementById("app");
const title = document.createElement("h1");
title.textContent = "Galeri";
app.appendChild(title);
const gallery = document.createElement("div");
gallery.className = "gallery";
app.appendChild(gallery);
const images = [
{ url: "https://picsum.photos/id/1/200/200", title: "Dağ manzarası", author: "Ayşe" },
{ url: "https://picsum.photos/id/2/200/200", title: "Şehir sokakları", author: "Mehmet" },
{ url: "https://picsum.photos/id/3/200/200", title: "Göl kıyısı", author: "Zeynep" }
];
async function fetchImages(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return await response.text();
} catch (error) {
console.log(error.message);
}
}
Kendini test et
-
await ne işe yarar?
const response = await fetch(url);- İsteği iptal eder
- Yanıtı önbelleğe alır
- Promise çözülene kadar bekletir
- Yanıtı dizeye çevirir
Cevabı göster
Promise çözülene kadar bekletir — Doğru! await, Promise çözülene kadar fonksiyonu bekletir.
-
response.ok denetimini tamamla
if (____) { throw new Error('HTTP ' + response.status); }Cevabı göster
if (!response.ok) { throw new Error('HTTP ' + response.status); } -
API kavramlarını eşleştir
- async
- Promise döndüren fonksiyon
- await
- Promise'i bekleten anahtar
- fetch
- Ağ isteği yapan fonksiyon
- response.ok
- Başarı durumu
- throw
- Hata fırlatma