Learn
← Previous Next →

Hari 23: Fetch API & HTTP Requests

65 min Last updated 09 Apr 2026

Fetch API — HTTP Requests Modern

// GET request
async function ambilPengguna(id) {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);

    if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
    }

    const data = await response.json();
    return data;
}

// POST request
async function buatPost(data) {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
    });
    return response.json();
}

// Parallel requests
async function ambilSemua() {
    const [user, posts] = await Promise.all([
        fetch("/api/user/1").then(r => r.json()),
        fetch("/api/posts").then(r => r.json()),
    ]);
    return { user, posts };
}

Error Handling & Timeout

async function fetchDenganTimeout(url, ms = 5000) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), ms);

    try {
        const res = await fetch(url, { signal: controller.signal });
        clearTimeout(timer);
        return res.json();
    } catch (e) {
        if (e.name === "AbortError") throw new Error("Request timeout");
        throw e;
    }
}

💡 Notice: Promise.all() menjalankan semua Promise secara paralel dan menunggu semuanya selesai. Jauh lebih cepat dari await berurutan.

Assignment

Simulasikan fetch dengan Promise. Buat fungsi simulasiFetch(id) yang return data user setelah 100ms. Gunakan async/await dan tangani error untuk id negatif.

Expected output:

User 1: user1@example.com
User 2: user2@example.com
Error: ID harus positif
JS script.js
Solution
Output