Performance: Data fetching with handlers
This concept affects page load speed and interaction responsiveness by controlling when and how data is fetched and rendered.
const cache = new Map(); async function handler(req) { if (cache.has('data')) { return new Response(JSON.stringify(cache.get('data')), { headers: { 'Content-Type': 'application/json' } }); } const response = await fetch('https://api.example.com/data'); const data = await response.json(); cache.set('data', data); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); }
async function handler(req) { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetch on every request | Minimal DOM nodes | Multiple reflows due to delayed data | High paint cost waiting for data | [X] Bad |
| Cached fetch with async handler | Minimal DOM nodes | Single reflow after first fetch | Lower paint cost with cached data | [OK] Good |
serve in Deno for data fetching?serve and handlerserve function listens for incoming HTTP requests and uses the handler function to decide how to respond.handler?serve function usageserve is called with the handler function as an argument to start the server.serve(handler); which passes the handler function properly.async function handler(req) {
if (req.url.endsWith('/hello')) {
return new Response('Hello World');
}
return new Response('Not Found', { status: 404 });
}http://localhost:8000/hello?async function handler(req) {
if (req.url === '/data') {
const data = await fetch('https://api.example.com/data');
return data.json();
}
return new Response('Not Found', { status: 404 });
}data.json() returns a Promise that must be awaited.data.json() without awaiting it, which returns a Promise instead of a Response object./user. Which handler function correctly fetches the JSON data and returns it as a JSON response?endsWith('/user') to match URL and awaits both fetch and response.json(), which is correct.Pass the test and this pattern moves unknown