Asenkron JavaScript i Anlayin!
Promise Nedir?
// (c) CodeMareFi - codemarefi.com.tr
const veriGetir = new Promise((resolve, reject) => {
setTimeout(() => resolve({ site: 'CodeMareFi' }), 1000);
});
veriGetir.then(data => console.log(data)).catch(err => console.error(err));
Async/Await
// (c) CodeMareFi - codemarefi.com.tr
async function veriGetir(id) {
try {
const res = await fetch('https://api.example.com/users/' + id);
if (!res.ok) throw new Error('HTTP Hatasi: ' + res.status);
return await res.json();
} catch (err) {
console.error(err.message);
return null;
}
}
Promise.all ile Paralel Istekler
// (c) CodeMareFi - codemarefi.com.tr
const [kullanicilar, postlar] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
]);
© CodeMareFi
Bu icerik codemarefi.com.tr ye aittir.