Send asynchronous browser requests with fetch, XMLHttpRequest, JSON, errors, and progressive UI.
Lessons
Hold a request open until new data is ready.
Long Polling is easiest to learn by reading the example, changing it, and observing the result.
async function subscribe() {
try {
const res = await fetch('/api/updates'); // server holds the request open
if (res.ok) {
const update = await res.json();
console.log('New data:', update);
}
} catch (error) {
console.error(error);
}
subscribe(); // immediately reopen the connection
}
subscribe();Practice the Long Polling example in a small scratch file, then explain what changed and why.