TypeScript asinxron dasturlash
TypeScript JavaScript-ning asinxron imkoniyatlarini statik yozish bilan yaxshilaydi, bu esa asinxron kodingizni oldindan aytib bo‘ladigan va saqlab turishga imkon beradi.
Ushbu qo‘llanma asosiy async/await’dan tortib, ilg‘or naqshlargacha bo‘lgan hamma narsani qamrab oladi.
Ushbu qo‘llanma JavaScript Promiselari va asinxron dasturlash bo‘yicha asosiy bilimlarni o‘z ichiga oladi.
Agar siz ushbu tushunchalar bilan tanish bo‘lsangiz, avval JavaScript Async qo‘llanmamizni ko‘rib chiqing.
TypeScript-dagi Promiselar
TypeScript JavaScript Promiselarini genericlar orqali tur xavfsizligi bilan yaxshilaydi.
Promise<T> T turidagi qiymat bilan yakunlanadigan yoki any turidagi sabab bilan bajarilmaydigan asinxron operatsiyani ifodalaydi.
Key Points:
Promise<T>- Umumiy tip, bundaThal qilingan qiymat turiPromise<void>- Qiymatni qaytarmaydigan Promiselar uchunPromise<never>- hech qachon resolve bo‘lmaydigan Promise’lar uchun (kam uchraydi)
Asosiy Promise namunasi
// Create a typed Promise that resolves to a string
const fetchGreeting = (): Promise<string> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("Hello, TypeScript!");
} else {
reject(new Error("Failed to fetch greeting"));
}
}, 1000);
});
};
// Using the Promise with proper type inference
fetchGreeting()
.then((greeting) => {
// TypeScript knows 'greeting' is a string
console.log(greeting.toUpperCase());
})
.catch((error: Error) => {
console.error("Error:", error.message);
});
O‘zingiz sinab ko‘ring »
Promise qilingan holatlar va oqim turi
pending → fulfilled (qiymat bilan: T) // Muvaffaqiyatli holat
pending → rejected (sabab bilan: any) // Xatolik holati
TypeScript ushbu holatlarni tip tizimi orqali kuzatib boradi, bu sizga muvaffaqiyat va xato holatlarini to‘g‘ri boshqarishingizni ta’minlaydi.
Promise<T>-dagi type parametri TypeScript-ga Promise qaysi turni hal qilishini bildiradi, bu esa turni yaxshiroq tekshirish va IDE-ni qo‘llab-quvvatlash imkonini beradi.
TypeScript bilan sinxronlash/kutish
TypeScript-ning async/await sintaksisi Promiselar bilan ishlashning yanada toza usulini ta’minlaydi, bu esa asinxron kodning ko‘rinishini va o‘zini sinxron kodga o‘xshatishini ta’minlaydi, shu bilan birga tip xavfsizligini ta’minlaydi.
Async/Awaitning asosiy afzalliklari
- Readability : Kuzatish osonroq bo‘lgan ketma-ket kod
- Error Handling : Sinxronlash va sinxronlash xatolari uchun try/catch funksiyasidan foydalaning
- Debugging : Sinxronga o‘xshash stek izlari bilan debug qilish osonroq
- Type Safety : To‘liq TypeScript turini chiqarish va tekshirish
Asosiy Async/Await misoli
// Define types for our API response
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
}
// Function that returns a Promise of User array
async function fetchUsers(): Promise<User[]> {
console.log('Fetching users...');
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
return [
{ id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin' },
{ id: 2, name: 'Bob', email: 'bob@example.com', role: 'user' }
];
}
// Async function to process users
async function processUsers() {
try {
// TypeScript knows users is User[]
const users = await fetchUsers();
console.log(`Fetched ${users.length} users`);
// Type-safe property access
const adminEmails = users
.filter(user => user.role === 'admin')
.map(user => user.email);
console.log('Admin emails:', adminEmails);
return users;
} catch (error) {
if (error instanceof Error) {
console.error('Failed to process users:', error.message);
} else {
console.error('An unknown error occurred');
}
throw error; // Re-throw to let caller handle
}
}
// Execute the async function
processUsers()
.then(users => console.log('Processing complete'))
.catch(err => console.error('Processing failed:', err));
O‘zingiz sinab ko‘ring »
Asinx funksiyasini qaytarish turlari
TypeScript-dagi barcha sinxronlash funksiyalari Promise-ni qaytaradi.
Qaytish turi avtomatik ravishda Promise-ga o‘raladi:
async function getString(): string { } // Error: must return Promise
async function getString(): Promise<string> { } // Correct
Promise.all bilan parallel bajarish
Parallel ravishda bir nechta asinxron operatsiyalarni bajaring va barchasi tugashini kuting:
interface Product {
id: number;
name: string;
price: number;
}
async function fetchProduct(id: number): Promise<Product> {
console.log(`Fetching product ${id}...`);
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
return { id, name: `Product ${id}`, price: Math.floor(Math.random() * 100) };
}
async function fetchMultipleProducts() {
try {
// Start all fetches in parallel
const [product1, product2, product3] = await Promise.all([
fetchProduct(1),
fetchProduct(2),
fetchProduct(3)
]);
const total = [product1, product2, product3]
.reduce((sum, product) => sum + product.price, 0);
console.log(`Total price: $${total.toFixed(2)}`);
} catch (error) {
console.error('Error fetching products:', error);
}
}
fetchMultipleProducts();
O‘zingiz sinab ko‘ring »
Eslatma: TypeScript-dagi barcha asenk funksiyalar Promise-ni qaytaradi.
Promise turi parametri Promise kalit so‘zidan keyin e’lon qilgan qaytish turiga mos keladi.
Asenkron operatsiyalar uchun callback funksiyasilarni yozish
An’anaviy callback funksiyasiqa asoslangan asinxron kod uchun TypeScript callback funksiyasi parametrlarini to‘g‘ri kiritishga yordam beradi:
Misol
// Define a type for the callback
type FetchCallback = (error: Error | null, data?: string) => void;
// Function that takes a typed callback
function fetchDataWithCallback(url: string, callback: FetchCallback): void {
// Simulate async operation
setTimeout(() => {
try {
// Simulate successful response
callback(null, "Response data");
} catch (error) {
callback(error instanceof Error ? error : new Error('Unknown error'));
}
}, 1000);
}
// Using the callback function
fetchDataWithCallback('https://api.example.com', (error, data) => {
if (error) {
console.error('Error:', error.message);
return;
}
// TypeScript knows data is a string (or undefined)
if (data) {
console.log(data.toUpperCase());
}
});
O‘zingiz sinab ko‘ring »
Promise kombinatsiyalar
TypeScript bir nechta Promiselar bilan ishlash uchun kuchli yordam turlari va usullarini taqdim etadi.
Ushbu usullar bir vaqtning o‘zida operatsiyalarni boshqarishga va ularning natijalarini xavfsiz tarzda boshqarishga yordam beradi.
Promiselarni birlashtirish usullari
Promise.all()- Barcha Promiselar hal qilinishini kutadiPromise.race()- birinchi hal qilingan Promise-ni qaytaradiPromise.allSettled()- barchasi yakunlanishini kutadi (muvaffaqiyatli yoki muvaffaqiyatsiz)Promise.any()- Birinchi bajarilgan Promise-ni qaytaradi
Promise.all - Parallel ijro
Bir nechta Promiselarni parallel ravishda bajaring va barchasi bajarilishini kuting.
Har qanday Promise rad etilsa, tezda muvaffaqiyatsiz bo‘ladi.
// Different types of promises
const fetchUser = (id: number): Promise<{ id: number; name: string }> =>
Promise.resolve({ id, name: `User ${id}` });
const fetchPosts = (userId: number): Promise<Array<{ id: number; title: string }>> =>
Promise.resolve([
{ id: 1, title: 'Post 1' },
{ id: 2, title: 'Post 2' }
]);
const fetchStats = (userId: number): Promise<{ views: number; likes: number }> =>
Promise.resolve({ views: 100, likes: 25 });
// Run all in parallel
async function loadUserDashboard(userId: number) {
try {
const [user, posts, stats] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchStats(userId)
]);
// TypeScript knows the types of user, posts, and stats
console.log(`User: ${user.name}`);
console.log(`Posts: ${posts.length}`);
console.log(`Likes: ${stats.likes}`);
return { user, posts, stats };
} catch (error) {
console.error('Failed to load dashboard:', error);
throw error;
}
}
// Execute with a user ID
loadUserDashboard(1);
O‘zingiz sinab ko‘ring »
Promise.race - birinchi bo‘lib hal qilish
Vaqt tugashi yoki bir nechta manbalardan birinchi muvaffaqiyatli javobni olish uchun foydalidir.
// Helper function for timeout
const timeout = (ms: number): Promise<never> =>
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms)
);
// Simulate API call with timeout
async function fetchWithTimeout<T>(
promise: Promise<T>,
timeoutMs: number = 5000
): Promise<T> {
return Promise.race([
promise,
timeout(timeoutMs).then(() => {
throw new Error(`Request timed out after ${timeoutMs}ms`);
}),
]);
}
// Usage example
async function fetchUserData() {
try {
const response = await fetchWithTimeout(
fetch('https://api.example.com/user/1'),
3000 // 3 second timeout
);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', (error as Error).message);
throw error;
}
}
O‘zingiz sinab ko‘ring »
Promise.allSettled - Barcha natijalarni boshqaring
Muvaffaqiyat yoki muvaffaqiyatsizlikdan qat’i nazar, barcha Promiselarning bajarilishini kutmoqchi bo‘lganingizda.
// Simulate multiple API calls with different outcomes
const fetchData = async (id: number) => {
// Randomly fail some requests
if (Math.random() > 0.7) {
throw new Error(`Failed to fetch data for ID ${id}`);
}
return { id, data: `Data for ${id}` };
};
// Process multiple items with individual error handling
async function processBatch(ids: number[]) {
const promises = ids.map(id =>
fetchData(id)
.then(value => ({ status: 'fulfilled' as const, value }))
.catch(reason => ({ status: 'rejected' as const, reason }))
);
// Wait for all to complete
const results = await Promise.allSettled(promises);
// Process results
const successful = results
.filter((result): result is PromiseFulfilledResult<{ status: 'fulfilled', value: any }> =>
result.status === 'fulfilled' &&
result.value.status === 'fulfilled'
)
.map(r => r.value.value);
const failed = results
.filter((result): result is PromiseRejectedResult |
PromiseFulfilledResult<{ status: 'rejected', reason: any }> => {
if (result.status === 'rejected') return true;
return result.value.status === 'rejected';
});
console.log(`Successfully processed: ${successful.length}`);
console.log(`Failed: ${failed.length}`);
return { successful, failed };
}
// Process a batch of IDs
processBatch([1, 2, 3, 4, 5]);
O‘zingiz sinab ko‘ring »
Ogohlantirish: Promise.all dan har xil turdagi Promiselar majmuasi bilan foydalanilganda, TypeScript natija turini barcha mumkin bo‘lgan turlar birlashmasi massivi sifatida ko‘rsatadi.
Aniqroq yozish uchun siz tur tasdiqlaridan foydalanishingiz yoki kutilgan tuzilmani belgilashingiz kerak bo‘lishi mumkin.
Asenkron kodda xatolik
TypeScript asinxron kodda turdagi xavfsiz xatolarni qayta ishlash uchun kuchli vositalarni taqdim etadi.
Keling, turli naqshlar va eng yaxshi amaliyotlarni ko‘rib chiqaylik.
Xatolarni bartaraf etish strategiyalari
- Try/Catch Blocks : Asinx/kutishda xatolarni qayta ishlash uchun
- Error Boundaries : Reaktsiya komponentlari uchun
- Result Types : Muvaffaqiyat/muvaffaqiyatsizlik bilan funktsional yondashuv
- Error Subclassing : Domenga xos xatolar uchun
Maxsus xato sinflari
Xatolarni yaxshiroq hal qilish uchun domenga xos xato turlarini yarating:
// Base error class for our application
class AppError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly details?: unknown
) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace?.(this, this.constructor);
}
}
// Specific error types
class NetworkError extends AppError {
constructor(message: string, details?: unknown) {
super(message, 'NETWORK_ERROR', details);
}
}
class ValidationError extends AppError {
constructor(
public readonly field: string,
message: string
) {
super(message, 'VALIDATION_ERROR', { field });
}
}
class NotFoundError extends AppError {
constructor(resource: string, id: string | number) {
super(
`${resource} with ID ${id} not found`,
'NOT_FOUND',
{ resource, id }
);
}
}
// Usage example
async function fetchUserData(userId: string): Promise<{ id: string; name: string }> {
try {
// Simulate API call
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
if (response.status === 404) {
throw new NotFoundError('User', userId);
} else if (response.status >= 500) {
throw new NetworkError('Server error', { status: response.status });
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
const data = await response.json();
// Validate response data
if (!data.name) {
throw new ValidationError('name', 'Name is required');
}
return data;
} catch (error) {
if (error instanceof AppError) {
// Already one of our custom errors
throw error;
}
// Wrap unexpected errors
throw new AppError(
'Failed to fetch user data',
'UNEXPECTED_ERROR',
{ cause: error }
);
}
}
// Error handling in the application
async function displayUserProfile(userId: string) {
try {
const user = await fetchUserData(userId);
console.log('User profile:', user);
} catch (error) {
if (error instanceof NetworkError) {
console.error('Network issue:', error.message);
// Show retry UI
} else if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
// Highlight the invalid field
} else if (error instanceof NotFoundError) {
console.error('Not found:', error.message);
// Show 404 page
} else {
console.error('Unexpected error:', error);
// Show generic error message
}
}
}
// Execute with example data
displayUserProfile('123');
O‘zingiz sinab ko‘ring »
Xatolarni qayta ishlash naqshlari
Xatolarni ishonchli hal qilish uchun quyidagi naqshlarni ko‘rib chiqing:
- Komponent darajasidagi xatolarni qayta ishlash uchun React-da Error Boundaries
- Result Objects kutilayotgan holatlar uchun istisnolar qo‘yish o‘rniga
- Global Error Handler qo‘lga kiritilmagan istisnolar uchun
- Xatolarni yozib olish va xabar qilish uchun Error Logging
TypeScript bilan asinxron iteratsiya
TypeScript asinxron iteratorlar va asinxron generatorlarini to‘g‘ri yozish bilan qo‘llab-quvvatlaydi:
Misol
// Async generator function
async function* generateNumbers(): AsyncGenerator<number, void, unknown> {
let i = 0;
while (i < 5) {
// Simulate async operation
await new Promise(resolve => setTimeout(resolve, 1000));
yield i++;
}
}
// Using the async generator
async function consumeNumbers() {
for await (const num of generateNumbers()) {
// TypeScript knows num is a number
console.log(num * 2);
}
}
O‘zingiz sinab ko‘ring »
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
