JavaScript is single-threaded and uses an event loop. Promise represents a future value. async/await is syntactic sugar over Promises that makes async code look synchronous. fetch is the built-in HTTP client.
| Name | Signature / Syntax | Description |
|---|---|---|
| Promise | new Promise((resolve, reject) => {}) | Create a Promise |
| Promise.resolve | Promise.resolve(value) → Promise | Create immediately-resolved Promise |
| Promise.reject | Promise.reject(error) → Promise | Create immediately-rejected Promise |
| Promise.all | Promise.all([p1,p2,p3]) → Promise<[]> | Resolve when ALL resolve; reject if any reject |
| Promise.allSettled | Promise.allSettled([p1,p2]) → Promise | Resolve when ALL settle (fulfilled or rejected) |
| Promise.race | Promise.race([p1,p2]) → Promise | Resolve/reject with whichever settles first |
| Promise.any | Promise.any([p1,p2]) → Promise | Resolve with first fulfilled; reject if all reject |
| .then | .then(onFulfilled, onRejected) | Chain fulfilled/rejected handlers |
| .catch | .catch(onRejected) | Handle rejection |
| .finally | .finally(fn) | Run fn regardless of outcome |
| async function | async function f() {} | Function that always returns a Promise |
| await | const x = await promise | Pause until Promise settles |
| try/catch with await | try { await fn() } catch(e) {} | Handle async errors |
| fetch | fetch(url, options) → Promise<Response> | Built-in HTTP client |
| response.json | response.json() → Promise<any> | Parse response body as JSON |
| response.text | response.text() → Promise<string> | Parse response body as text |
| response.ok | response.ok → bool | True if status 200-299 |
| response.status | response.status → number | HTTP status code |
| AbortController | new AbortController() | Cancel fetch requests |
| setTimeout | setTimeout(fn, ms) → id | Run fn after delay |
| setInterval | setInterval(fn, ms) → id | Run fn repeatedly every ms |
| clearTimeout | clearTimeout(id) | Cancel scheduled timeout |
| queueMicrotask | queueMicrotask(fn) | Schedule fn as microtask (before next macro) |
| for await...of | for await (const x of asyncIterable) | Iterate async iterables |
Run with node script.js or save as HTML and open in browser.
// Async/Await & Promises
// --- Basic Promise ---
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const fetchUser = async (id) => {
await delay(10); // simulate network
if (id <= 0) throw new Error(`Invalid id: \${id}`);
return { id, name: `User\${id}`, role: id === 1 ? 'admin' : 'user' };
};
// --- async/await with error handling ---
async function main() {
// Sequential
try {
const user = await fetchUser(1);
console.log('User:', user);
} catch (e) {
console.error('Error:', e.message);
}
// Parallel with Promise.all
const [u1, u2, u3] = await Promise.all([fetchUser(1), fetchUser(2), fetchUser(3)]);
console.log('All users:', [u1, u2, u3].map(u => u.name));
// Promise.allSettled — handles mixed success/failure
const results = await Promise.allSettled([
fetchUser(1), fetchUser(-1), fetchUser(3)
]);
results.forEach((r, i) => {
if (r.status === 'fulfilled') console.log(` ✅ \${i}: \${r.value.name}`);
else console.log(` ❌ \${i}: \${r.reason.message}`);
});
// Race (first wins)
const fast = await Promise.race([delay(50).then(()=>'slow'), delay(10).then(()=>'fast')]);
console.log('Race winner:', fast); // fast
// Real fetch example (Node 18+ or browser)
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
console.log('Post title:', data.title.substring(0, 40));
} catch (e) {
console.log('Fetch error (offline?):', e.message);
}
}
main().catch(console.error);
// node script.js (Node 18+ has built-in fetch)