Learn
← Previous Next →

Hari 19: Async TypeScript Patterns

60 min Last updated 09 Apr 2026

Async/Await dengan Type Safety

interface ApiResponse {
    data: T;
    status: number;
    message: string;
    timestamp: string;
}

async function fetchData(url: string): Promise> {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json() as Promise>;
}

// Result pattern untuk async
type AsyncResult =
    | { ok: true;  value: T }
    | { ok: false; error: E };

async function safeAsync(
    fn: () => Promise
): Promise> {
    try {
        return { ok: true, value: await fn() };
    } catch (e) {
        return { ok: false, error: e as Error };
    }
}

💡 Notice: 5 → *2=10 → delay(50ms, tetap 10) → +3=13 → "Hasil: 13". Async pipeline memproses data secara berurutan dengan dukungan operasi async.

Assignment

Buat fungsi asyncPipeline yang menjalankan array fungsi async secara berurutan, masing-masing menerima output sebelumnya. Test dengan transformasi angka.

Expected output:

Hasil: 13
TS index.ts
Solution
Output