Chuyển đến nội dung chính
eLearner.app
Mô-đun 7 · Bài học 3 trong tổng số 427/32 trong khóa học~14 min
Bài học theo mô-đun (3/4)

lấy (mô phỏng)

On a real page, fetch(url) calls a server. Here in the learning browser we cannot talk to external servers, so we will use a "fake" fetch: in the tests, a globalThis.fetch is injected that returns predefined data, so you can practice on the logic without depending on the network.

The API you care about is the same as the real one:

JS
const response = await fetch('/api/utenti');
const data = await response.json();

fetch(url) returns a Promise that resolves to a Response object. Response.json() returns in turn a Promise with the parsed body. So you need two awaits.

Complete example

JS
async function loadUsers() {
  const response = await fetch('/api/utenti');
  const users = await response.json();
  return users;
}

const list = await loadUsers();
// [{...}, {...}]

Checking if it succeeded

fetch does not throw if the server responds with an error status (404, 500). It still gives you a Response, but with ok: false:

JS
const r = await fetch('/api/utenti');
if (!r.ok) {
  throw new Error(`HTTP ${r.status}`);
}
const data = await r.json();

fetch only throws if the network fails (no connection, DNS, ...).

Multiple requests in parallel: Promise.all

If you need to make N independent calls, launch them together and wait for all of them with Promise.all:

JS
const [u, p] = await Promise.all([
  fetch('/api/utenti').then((r) => r.json()),
  fetch('/api/prodotti').then((r) => r.json()),
]);

Serially with two consecutive awaits it would take almost twice the time (sum); in parallel it is the maximum of the two (the slowest).

Try it

tập thể dục#js.m7.l3.e1
Nỗ lực: 0Đang tải…

Define `loadUsers()` async: call fetch('/api/utenti'), then .json() to obtain the users array, and return it.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Two awaits: one on fetch, one on .json().

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#js.m7.l3.e2
Nỗ lực: 0Đang tải…

Define `loadInParallel(urls)` async: receive an array of URLs, do fetch + .json() on each one in parallel with Promise.all, and return an array of the received JSON values, in the same order.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

urls.map((u) => fetch(u).then(r => r.json())) and Promise.all.

Giải pháp khả dụng sau 3 lần thử