javascript
const p = Promise.resolve({ ok: true });Promises, async/await, fetch, timers, generators, async iterables, and event loop patterns.
Create, chain, settle, and compose promises.
const p = Promise.resolve({ ok: true });const p = Promise.reject(new Error("Boom"));fetchData()
.then((data) => transform(data))
.catch((err) => console.error(err))
.finally(() => console.log("done"));const [user, posts] = await Promise.all([getUser(), getPosts()]);const results = await Promise.allSettled(tasks);const winner = await Promise.race([fast(), slow()]);const firstSuccess = await Promise.any(providers);Write linear async flows and handle async errors.
async function loadUser(id) {
const res = await fetch(`/api/users/${id}`);
return res.json();
}try {
const data = await loadUser(1);
console.log(data);
} catch (err) {
console.error(err);
}for (const url of urls) {
const res = await fetch(url);
console.log(await res.text());
}const html = await Promise.all(urls.map(async (url) => {
const res = await fetch(url);
return res.text();
}));await (async () => {
const config = await loadConfig();
console.log(config);
})();HTTP requests, JSON handling, abort signals, timeouts, and retries.
const res = await fetch("/api/items");
const data = await res.json();const res = await fetch("/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
});const controller = new AbortController();
setTimeout(() => controller.abort(), 3000);
await fetch(url, { signal: controller.signal });await Promise.race([
fetch(url),
new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 3000)),
]);const form = new FormData();
form.append("file", file);
await fetch("/upload", { method: "POST", body: form });async function withRetry(fn, retries = 3) {
let lastError;
for (let i = 0; i < retries; i++) {
try { return await fn(); } catch (err) { lastError = err; }
}
throw lastError;
}setTimeout, setInterval, microtasks, debouncing, and throttling.
const timeoutId = setTimeout(() => {
console.log("Later");
}, 1000);clearTimeout(timeoutId);const intervalId = setInterval(tick, 1000);clearInterval(intervalId);queueMicrotask(() => {
console.log("Runs before next macrotask");
});function debounce(fn, wait = 250) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}function throttle(fn, wait = 250) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn(...args);
}
};
}Custom iterables, generators, and for-await-of loops.
function* ids() {
yield 1;
yield 2;
yield 3;
}const gen = ids();
gen.next(); // { value: 1, done: false }function* combined() {
yield* [1, 2];
yield* [3, 4];
}const range = {
from: 1,
to: 3,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) yield i;
},
};async function* pages() {
let page = 1;
while (page <= 3) {
yield await fetch(`/api/page/${page++}`).then((r) => r.json());
}
}for await (const page of pages()) {
console.log(page);
}