Fetch Item Shop — JavaScript

Stock Bang Arka's prize rack with fetch couriers to Bang Dodi's warehouse: 12 levels of fetch, async/await, res.ok, JSON and Promise.all.

What the levels ask

  1. Request the item list from GET /api/items, parse its JSON, show it on the shelf (rak), and return the items array.
  2. Fetch /api/items, show every item on the shelf, but return only the array of their NAMES (nama): ["Pedang", "Perisai", …].
  3. Only items with stok > 0 may go on display. Show and return the filtered array.
  4. GET /api/items/99 answers 404 with a body { error }. If !res.ok: call rak.pesan("Item tidak ada") ("item not found") and return null. Don't treat the error body as data.
  5. The network to /api/items is down (fetch throws). Catch the error: call rak.pesan("Gudang tutup") ("depot closed") and return [] instead of crashing.
  6. Call rak.loading(true) BEFORE the fetch and rak.loading(false) AFTER the data is ready. The order is judged by when the calls happen.
  7. GET /api/toko answers { nama, itemUrl }. Take itemUrl from that answer, then fetch that URL to get the items. Show and return the items.
  8. Fetch /api/items/1, /api/items/2 and /api/items/3 at the same time (not one after another) with Promise.all. Show and return [item1, item2, item3].
  9. GET /api/stok fails (500) twice before it succeeds. Repeat the request until res.ok, at most 3 times, then show and return the data.
  10. GET /api/lambat takes 600 ms. Cap the wait at 100 ms with Promise.race: if the fetch loses, call rak.pesan("Waktu habis") ("time's up") and return []. muatToko must finish in < 300 ms.
  11. Send POST /api/beli with the header Content-Type: application/json and the JSON body { id: 2, jumlah: 1 }. Return data.struk (the receipt) from the answer and show your receipt with rak.pesan.
  12. Loading → fetch /api/items → filter stok > 0 → fetch each item's price from /api/harga/:id at the same time → merge ({ ...item, harga: hargaBaru }) → show → loading done → return the result. Wrap it in a try/catch that calls rak.pesan("Gudang tutup").