
JavaScript Async/Await Detaylı Rehberi: Modern Asenkron Programlama
JavaScript Async/Await Detaylı Rehberi: Modern Asenkron Programlama
JavaScript'te asenkron programlama, modern web uygulamalarının temel taşlarından biridir. Async/await, Promise'ların üzerine inşa edilmiş ve asenkron kod yazmayı daha okunabilir hale getiren güçlü bir özelliktir. Bu rehberde, async/await'i sıfırdan öğrenecek ve pratik örneklerle nasıl kullanacağınızı göreceksiniz.
Asenkron Programlama Nedir?
Asenkron programlama, uzun süren işlemlerin (API çağrıları, dosya okuma, veritabanı sorguları) diğer kodların çalışmasını engellemeden arka planda yürütülmesini sağlar.
Senkron vs Asenkron
// Senkron kod - Bloklar
function syncFunction() {
console.log('1. Başladı');
const result = heavyOperation(); // Bu işlem bitene kadar bekler
console.log('2. Bitti:', result);
console.log('3. Devam ediyor');
}
// Asenkron kod - Bloklamaz
async function asyncFunction() {
console.log('1. Başladı');
const result = await heavyOperation(); // Diğer kodlar çalışmaya devam eder
console.log('2. Bitti:', result);
console.log('3. Devam ediyor');
}
Promise Temelleri
Async/await, Promise'ların üzerine inşa edilmiştir. Önce Promise'ları anlayalım:
// Promise oluşturma
const myPromise = new Promise((resolve, reject) => {
// Asenkron işlem
setTimeout(() => {
const random = Math.random();
if (random > 0.5) {
resolve('Başarılı!');
} else {
reject('Hata oluştu!');
}
}, 1000);
});
// Promise kullanımı
myPromise
.then(result => console.log('Sonuç:', result))
.catch(error => console.error('Hata:', error));
Async/Await Temelleri
1. Async Fonksiyonlar
// Async fonksiyon tanımlama
async function fetchUserData() {
// Bu fonksiyon her zaman bir Promise döner
return 'Kullanıcı verisi';
}
// Arrow function ile
const fetchData = async () => {
return 'Veri';
};
// Class method ile
class UserService {
async getUser(id) {
return `Kullanıcı ${id}`;
}
}
2. Await Kullanımı
async function getUserInfo() {
try {
console.log('Kullanıcı bilgileri alınıyor...');
// await ile Promise'ın resolve olmasını bekler
const user = await fetchUser();
console.log('Kullanıcı:', user);
const posts = await fetchUserPosts(user.id);
console.log('Gönderiler:', posts);
return { user, posts };
} catch (error) {
console.error('Hata:', error);
throw error;
}
}
Pratik Örnekler
1. API Çağrıları
// Fetch API ile kullanım
async function fetchUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error('API çağrısı başarısız:', error);
throw error;
}
}
// Kullanım
async function displayUser() {
try {
const user = await fetchUserData(123);
console.log('Kullanıcı:', user.name);
} catch (error) {
console.error('Kullanıcı yüklenemedi:', error);
}
}
2. Paralel İşlemler
// Paralel Promise'lar
async function fetchAllData() {
try {
// Tüm Promise'lar aynı anda başlatılır
const [users, posts, comments] = await Promise.all([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
]);
const [usersData, postsData, commentsData] = await Promise.all([
users.json(),
posts.json(),
comments.json()
]);
return { users: usersData, posts: postsData, comments: commentsData };
} catch (error) {
console.error('Veri yüklenirken hata:', error);
throw error;
}
}
// Promise.allSettled - Bazıları başarısız olsa bile devam eder
async function fetchDataWithFallback() {
const results = await Promise.allSettled([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
]);
const data = {};
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
data[`data${index}`] = result.value;
} else {
console.error(`Veri ${index} yüklenemedi:`, result.reason);
}
});
return data;
}
3. Sequential vs Parallel
// Sequential (Sıralı) - Yavaş
async function fetchSequential() {
const start = Date.now();
const user1 = await fetchUser(1); // 1 saniye bekler
const user2 = await fetchUser(2); // 1 saniye bekler
const user3 = await fetchUser(3); // 1 saniye bekler
console.log('Toplam süre:', Date.now() - start); // ~3000ms
return [user1, user2, user3];
}
// Parallel (Paralel) - Hızlı
async function fetchParallel() {
const start = Date.now();
const [user1, user2, user3] = await Promise.all([
fetchUser(1),
fetchUser(2),
fetchUser(3)
]);
console.log('Toplam süre:', Date.now() - start); // ~1000ms
return [user1, user2, user3];
}
Error Handling
1. Try-Catch ile Hata Yönetimi
async function handleErrors() {
try {
const data = await fetchData();
return data;
} catch (error) {
if (error.name === 'NetworkError') {
console.error('Ağ hatası:', error);
return { error: 'İnternet bağlantısı yok' };
} else if (error.status === 404) {
console.error('Veri bulunamadı:', error);
return { error: 'Veri bulunamadı' };
} else {
console.error('Bilinmeyen hata:', error);
throw error; // Hatayı yukarı fırlat
}
}
}
2. Custom Error Sınıfları
class APIError extends Error {
constructor(message, status, url) {
super(message);
this.name = 'APIError';
this.status = status;
this.url = url;
}
}
async function fetchWithCustomError() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new APIError(
`HTTP ${response.status}: ${response.statusText}`,
response.status,
response.url
);
}
return await response.json();
} catch (error) {
if (error instanceof APIError) {
console.error(`API Hatası (${error.status}):`, error.message);
} else {
console.error('Beklenmeyen hata:', error);
}
throw error;
}
}
3. Retry Mekanizması
async function fetchWithRetry(url, maxRetries = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.log(`Deneme ${attempt}/${maxRetries} başarısız:`, error.message);
if (attempt === maxRetries) {
throw new Error(`Maksimum deneme sayısına ulaşıldı: ${error.message}`);
}
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
Advanced Patterns
1. Async Iterator
async function* asyncGenerator() {
const urls = ['/api/users', '/api/posts', '/api/comments'];
for (const url of urls) {
try {
const response = await fetch(url);
const data = await response.json();
yield data;
} catch (error) {
yield { error: error.message };
}
}
}
// Kullanım
async function processData() {
for await (const data of asyncGenerator()) {
if (data.error) {
console.error('Hata:', data.error);
} else {
console.log('Veri:', data);
}
}
}
2. Async Queue
class AsyncQueue {
constructor() {
this.queue = [];
this.processing = false;
}
async add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.process();
});
}
async process() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
while (this.queue.length > 0) {
const { task, resolve, reject } = this.queue.shift();
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
}
}
this.processing = false;
}
}
// Kullanım
const queue = new AsyncQueue();
async function addTask() {
const result = await queue.add(async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
return 'Task tamamlandı';
});
console.log(result);
}
3. Debounce ve Throttle
// Debounce
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Throttle
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Async debounce
function asyncDebounce(func, wait) {
let timeout;
return function(...args) {
return new Promise((resolve, reject) => {
clearTimeout(timeout);
timeout = setTimeout(async () => {
try {
const result = await func.apply(this, args);
resolve(result);
} catch (error) {
reject(error);
}
}, wait);
});
};
}
// Kullanım
const debouncedSearch = asyncDebounce(async (query) => {
const response = await fetch(`/api/search?q=${query}`);
return response.json();
}, 300);
Performance Optimizasyonu
1. Memory Leaks Önleme
// ❌ Yanlış - Memory leak
async function badExample() {
const controller = new AbortController();
setTimeout(async () => {
const response = await fetch('/api/data', {
signal: controller.signal
});
// Bu kod çalışmayabilir çünkü component unmount olmuş olabilir
}, 1000);
}
// ✅ Doğru - Cleanup ile
function useAsyncEffect() {
const [data, setData] = useState(null);
useEffect(() => {
let isMounted = true;
const controller = new AbortController();
const fetchData = async () => {
try {
const response = await fetch('/api/data', {
signal: controller.signal
});
const result = await response.json();
if (isMounted) {
setData(result);
}
} catch (error) {
if (error.name !== 'AbortError' && isMounted) {
console.error('Hata:', error);
}
}
};
fetchData();
return () => {
isMounted = false;
controller.abort();
};
}, []);
return data;
}
2. Caching
class AsyncCache {
constructor() {
this.cache = new Map();
}
async get(key, fetcher, ttl = 60000) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
const data = await fetcher();
this.cache.set(key, {
data,
timestamp: Date.now()
});
return data;
}
clear() {
this.cache.clear();
}
}
// Kullanım
const cache = new AsyncCache();
async function fetchUserWithCache(userId) {
return cache.get(
`user-${userId}`,
() => fetch(`/api/users/${userId}`).then(r => r.json()),
300000 // 5 dakika cache
);
}
Testing Async Code
1. Jest ile Testing
// Async test
describe('User API', () => {
test('should fetch user data', async () => {
const user = await fetchUser(1);
expect(user).toHaveProperty('id');
expect(user).toHaveProperty('name');
});
test('should handle errors', async () => {
await expect(fetchUser(999)).rejects.toThrow('User not found');
});
});
// Mock ile testing
jest.mock('./api');
test('should handle API errors', async () => {
fetchUser.mockRejectedValue(new Error('Network error'));
await expect(fetchUser(1)).rejects.toThrow('Network error');
});
2. Error Boundary Testing
class AsyncErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Async Error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <div>Bir hata oluştu: {this.state.error.message}</div>;
}
return this.props.children;
}
}
Best Practices
1. Kod Organizasyonu
// ❌ Yanlış - Karmaşık async fonksiyon
async function badFunction() {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
const comments = await fetchComments(posts[0].id);
const likes = await fetchLikes(comments[0].id);
// ... daha fazla nested await
}
// ✅ Doğru - Modüler yaklaşım
async function getUserData(userId) {
const user = await fetchUser(userId);
return user;
}
async function getPostData(userId) {
const posts = await fetchPosts(userId);
return posts;
}
async function getCommentData(postId) {
const comments = await fetchComments(postId);
return comments;
}
async function goodFunction(userId) {
const [user, posts] = await Promise.all([
getUserData(userId),
getPostData(userId)
]);
const comments = posts.length > 0
? await getCommentData(posts[0].id)
: [];
return { user, posts, comments };
}
2. Error Handling Patterns
// Result pattern
class Result {
constructor(success, data, error) {
this.success = success;
this.data = data;
this.error = error;
}
static success(data) {
return new Result(true, data, null);
}
static failure(error) {
return new Result(false, null, error);
}
}
async function safeAsyncOperation(operation) {
try {
const data = await operation();
return Result.success(data);
} catch (error) {
return Result.failure(error);
}
}
// Kullanım
const result = await safeAsyncOperation(() => fetchUser(1));
if (result.success) {
console.log('Kullanıcı:', result.data);
} else {
console.error('Hata:', result.error);
}
Sonuç
Async/await, JavaScript'te asenkron programlama yapmayı çok daha kolay ve okunabilir hale getirir. Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, modern web uygulamaları geliştirebilirsiniz.
Önemli Noktalar:
- Async fonksiyonlar her zaman Promise döner
- Await sadece async fonksiyonlarda kullanılabilir
- Error handling için try-catch kullanın
- Paralel işlemler için Promise.all kullanın
- Memory leak'leri önlemek için cleanup yapın
Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, asenkron JavaScript programlama becerilerinizi geliştirebilirsiniz.
İlgili Kaynaklar: