Created
August 14, 2025 23:52
-
-
Save zachary/44f0cc2399acabb6d9d1f9db0f9b4a95 to your computer and use it in GitHub Desktop.
js promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Java Script Promises Cheatsheet (Part 1) | |
| * created by @e_opore on X | |
| * Core Basics & Consumption | |
| */ | |
| // 1) creating a promise | |
| const p = new Promise((resolve, reject) => { | |
| const ok = true; | |
| if (ok) resolve("done"); | |
| else reject(new Error("nope")); | |
| }); | |
| // 2) consuming with .then / .catch / .finally | |
| p.then(value => { | |
| console.log("value:", value); | |
| return value + "!"; | |
| }) | |
| .then(next => { | |
| console.log("chained:", next); | |
| }) | |
| .catch(err => { | |
| console.log("caught:", err); | |
| }) | |
| .finally(()=>{ | |
| console.log("always runs (clenaup)"); | |
| }); | |
| // 3) chaining rules (return vs throw) | |
| Promise.resolve(2) | |
| .then(x=> x*2) | |
| .then(x => Promise.resolve(x+1)) | |
| .then(x => { throw new Error("boom at "+x); }) | |
| .catch(err => console.log("error flows to here:", err.message)); | |
| // 4) static helpers | |
| Promise.resolve("instant").then(console.log); | |
| Promise.reject(new Error("instant error")).catch(e => console.log(e.message)); | |
| Promise.all([Promise.resolve(1), Promise.resolve(2)]) | |
| .then(arr => console.log("all:", arr)); | |
| Promise.allSettled([ | |
| Promise.resolve(1), | |
| Promise.reject(new Error("bad")) | |
| ]).then(results => console.log("allSettled:", results)); | |
| Promise.race([ | |
| new Promise(r => setTimeout(() => r("A first"),50)), | |
| new Promise(r => setTimeout(() => r("B later"), 100)), | |
| ]).then(console.log); | |
| Promise.any([ | |
| Promise.reject(new Error("x")), | |
| Promise.resolve("y"), | |
| Promise.reject(new Error("z")), | |
| ]).then(v => console.log("any:",v)) | |
| .catch(aggErr => console.log(aggErr.errors)); | |
| /** | |
| * Java Script Promises Cheatsheet (Part 2) | |
| * created by @e_opore on X | |
| * Timing, Utilities, and Execution Patterns | |
| */ | |
| // 5) Microtask vs Macrotask | |
| console.log("start"); | |
| Promise.resolve(). then(() => console. log("microtask")); | |
| setTimeout(() => console. log("macrotask"), 0); | |
| console. log("end"); | |
| // 6) Promisify | |
| const promisify = fn => (... args) => | |
| new Promise((resolve, reject) => | |
| fn(... args, (err, result) => err ? reject(err) : resolve(result)) | |
| ); | |
| function legacyAdd(a, b, cb) { setTimeout(() => cb(null, a + b), 20); } | |
| const addAsync = promisify(legacyAdd); | |
| addAsync(2, 3). then(console. log); | |
| // 7) Delay helper | |
| const delay = (ms, value) => | |
| new Promise(resolve => setTimeout(() => resolve(value), ms)); | |
| delay(100, "after 100 ms"). then(console. log); | |
| // 8) Timeouts & cancellation | |
| const withTimeout = (promise, ms, label ="Operation") => { | |
| const timeout = new Promise((_, reject) => | |
| setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms) | |
| ); | |
| return Promise.race([promise, timeout]); | |
| }; | |
| async function fetchWithAbort(url, ms = 3000) { | |
| const ctrl = new AbortController(); | |
| const t = setTimeout(() => ctrl.abort(), ms); | |
| try { | |
| const res = await fetch(url, { signal: ctrl. signal }); | |
| return res. text(); | |
| } finally { | |
| clearTimeout(t); | |
| } | |
| } | |
| // 9) Sequential vs Parallel | |
| const tasks = [1, 2, 3]. map(i => () => delay(100 * i, i)); | |
| Promise. all(tasks. map(fn => fn())). then(v => console. log("parallel:", v)); | |
| async function runSequential(fns) { | |
| const out = []; | |
| for (const fn of fns) out.push(await fn()); | |
| return out; | |
| } | |
| runSequential(tasks). then(v => console. log("sequential:", v)); | |
| /** | |
| * Java Script Promises Cheatsheet (Part 3) | |
| * created by @e_opore on X | |
| * Advanced Patterns & Gotchas | |
| */ | |
| // 10) Retry with exponential backoff | |
| async function retry(fn, { | |
| retries = 3, | |
| baseDelay = 200, | |
| factor = 2, | |
| onRetry = (e, attempt) => console. warn(`Retry ${attempt}:`, e. message), | |
| } = {}){ | |
| let attempt = 0, delayMs = baseDelay; | |
| while (true) { | |
| try { | |
| return await fn(); | |
| } catch (e) { | |
| if (attempt >= retries) throw e; | |
| attempt++; | |
| onRetry(e, attempt); | |
| await delay(delayMs); | |
| delayMs *= factor; | |
| } | |
| } | |
| } | |
| // 11) Concurrency limit | |
| async function mapPool(items, mapper, concurrency = 5) { | |
| const ret = [1]; | |
| let i= 0; | |
| const workers = Array. from({ length: Math. min(concurrency, items. length) }, async function worker() { | |
| while (i < items. length) { | |
| const idx = i++; | |
| ret[idx] = await mapper(items[idx], idx); | |
| } | |
| }); | |
| await Promise.all(workers); | |
| return ret; | |
| } | |
| // 12) Safe all Settled result parsing | |
| async function safeAll(promises) { | |
| const settled = await Promise. allSettled(promises); | |
| return { | |
| values: settled. filter(r => r. status == "fulfilled"). map(r => r. value), | |
| errors: settled. filter(r => r. status == "rejected"). map(r => r. reason) | |
| }; | |
| } | |
| // 13) async/await interop | |
| async function example() { | |
| try { | |
| const a = await Promise. resolve(1); | |
| const b = await delay(50, 2); | |
| return a + b; | |
| } catch (e) { | |
| throw e; | |
| } | |
| } | |
| example(). then(console. log). catch(console. error); | |
| // 14) Gotchas | |
| Promise.resolve(1). then(x => { x + 1; }). then(console. log); // undefined | |
| Promise.resolve(). then(() => { throw new Error("lost"); }).catch(() => {}); | |
| // 15) Small utilities | |
| const from = v => Promise. resolve(v); | |
| const to = p => p. then(v => [null, v]). catch(e => [e]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment