Load a list from a stand-in server, and show it on the page.
What to build
An async function that requests the products and draws them.
Requirements
- Call
fakeFetch("/api/products")once when the page loads. - Read the body with
json(). - Add one
lito#productsfor each product, with the textNAME: PRICE. - When finished, set
#statustoLoaded N products.
Constraints
Use await. Use textContent, not innerHTML. Do not change the first script, which stands in for a server.
Example
Pen: 10
Why it works
Each await pauses only your function, so the page stays responsive while the data is on its way. In a real project, only the word fakeFetch would change.
Hints
Hint 1
Write an async function, and call it once.
Hint 2
await fakeFetch(...), then await response.json().
Hint 3
Make an li for each product, and set the status at the end.
Solution
Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Products</title>
</head>
<body>
<p id="status" role="status">Loading...</p>
<ul id="products"></ul>
<script>
// A stand-in for a real server, because this page has no network.
function fakeFetch(url) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
ok: true,
status: 200,
json: async () => [
{ name: "Pen", price: 10 },
{ name: "Notebook", price: 60 },
{ name: "Ruler", price: 25 },
],
});
}, 30);
});
}
</script>
<script>
async function load() {
const response = await fakeFetch("/api/products");
const products = await response.json();
const list = document.querySelector("#products");
for (const product of products) {
const li = document.createElement("li");
li.textContent = product.name + ": " + product.price;
list.append(li);
}
document.querySelector("#status").textContent = "Loaded " + products.length + " products";
}
load();
</script>
</body>
</html>