From d8908561907ab804ff0d23d44536116885cdb2ff Mon Sep 17 00:00:00 2001 From: Gabriel Matossian Date: Wed, 4 Nov 2026 14:42:26 -0800 Subject: [PATCH] Add accepted JavaScript and RxJS reference topics --- content/topics/angular/topic.md | 2 +- .../topics/javascript-async-await/sources.md | 8 + .../topics/javascript-async-await/topic.md | 64 +++++ .../javascript-async-concurrency/sources.md | 8 + .../javascript-async-concurrency/topic.md | 59 ++++ .../javascript-event-loop/execution-cycle.svg | 241 ++++++++++++++++ .../topics/javascript-event-loop/sources.md | 12 + content/topics/javascript-event-loop/topic.md | 97 +++++++ .../javascript-execution/busy-thread.svg | 236 ++++++++++++++++ .../topics/javascript-execution/sources.md | 10 + content/topics/javascript-execution/topic.md | 58 ++++ .../javascript-polling/polling-timing.svg | 260 ++++++++++++++++++ content/topics/javascript-polling/sources.md | 11 + content/topics/javascript-polling/topic.md | 72 +++++ .../javascript-promise-chains/sources.md | 10 + .../topics/javascript-promise-chains/topic.md | 142 ++++++++++ .../javascript-promise-states/sources.md | 8 + .../topics/javascript-promise-states/topic.md | 58 ++++ content/topics/javascript-promises/sources.md | 12 + content/topics/javascript-promises/topic.md | 61 ++++ .../sources.md | 8 + .../topic.md | 40 +++ content/topics/javascript-timers/sources.md | 7 + content/topics/javascript-timers/topic.md | 43 +++ content/topics/javascript/topic.md | 11 +- .../rxjs-notification-timing/sources.md | 9 + .../topics/rxjs-notification-timing/topic.md | 41 +++ .../rxjs-subscriptions-and-cleanup/sources.md | 11 + .../rxjs-subscriptions-and-cleanup/topic.md | 59 ++++ contracts/runtime-catalog.ts | 7 + docs/content-storage.md | 19 +- docs/visual-design.md | 4 + public/icons/topics/angular-LICENSE.txt | 10 + public/icons/topics/angular.svg | 52 ++++ public/icons/topics/async.svg | 17 ++ public/icons/topics/event-loop.svg | 19 ++ public/icons/topics/execution.svg | 20 ++ public/icons/topics/observable.svg | 20 ++ public/icons/topics/promise.svg | 22 ++ public/icons/topics/timer.svg | 18 ++ src/app/browse/topic-index-page.spec.ts | 2 +- src/app/catalog/catalog.service.spec.ts | 2 +- src/app/ui/topic-icon/topic-icon.css | 7 + 43 files changed, 1868 insertions(+), 9 deletions(-) create mode 100644 content/topics/javascript-async-await/sources.md create mode 100644 content/topics/javascript-async-await/topic.md create mode 100644 content/topics/javascript-async-concurrency/sources.md create mode 100644 content/topics/javascript-async-concurrency/topic.md create mode 100644 content/topics/javascript-event-loop/execution-cycle.svg create mode 100644 content/topics/javascript-event-loop/sources.md create mode 100644 content/topics/javascript-event-loop/topic.md create mode 100644 content/topics/javascript-execution/busy-thread.svg create mode 100644 content/topics/javascript-execution/sources.md create mode 100644 content/topics/javascript-execution/topic.md create mode 100644 content/topics/javascript-polling/polling-timing.svg create mode 100644 content/topics/javascript-polling/sources.md create mode 100644 content/topics/javascript-polling/topic.md create mode 100644 content/topics/javascript-promise-chains/sources.md create mode 100644 content/topics/javascript-promise-chains/topic.md create mode 100644 content/topics/javascript-promise-states/sources.md create mode 100644 content/topics/javascript-promise-states/topic.md create mode 100644 content/topics/javascript-promises/sources.md create mode 100644 content/topics/javascript-promises/topic.md create mode 100644 content/topics/javascript-rendering-and-yielding/sources.md create mode 100644 content/topics/javascript-rendering-and-yielding/topic.md create mode 100644 content/topics/javascript-timers/sources.md create mode 100644 content/topics/javascript-timers/topic.md create mode 100644 content/topics/rxjs-notification-timing/sources.md create mode 100644 content/topics/rxjs-notification-timing/topic.md create mode 100644 content/topics/rxjs-subscriptions-and-cleanup/sources.md create mode 100644 content/topics/rxjs-subscriptions-and-cleanup/topic.md create mode 100644 public/icons/topics/angular-LICENSE.txt create mode 100644 public/icons/topics/angular.svg create mode 100644 public/icons/topics/async.svg create mode 100644 public/icons/topics/event-loop.svg create mode 100644 public/icons/topics/execution.svg create mode 100644 public/icons/topics/observable.svg create mode 100644 public/icons/topics/promise.svg create mode 100644 public/icons/topics/timer.svg diff --git a/content/topics/angular/topic.md b/content/topics/angular/topic.md index 747ab34..9eb2c33 100644 --- a/content/topics/angular/topic.md +++ b/content/topics/angular/topic.md @@ -3,7 +3,7 @@ id: 'cbbb9857-d3fa-47b8-8b47-d91b3f3dde7f' title: 'Angular' status: 'accepted' summary: 'Application setup, components, reactive state, services and HTTP integration.' -iconKey: 'architecture' +iconKey: 'angular' domains: - 'javascript' kind: 'area' diff --git a/content/topics/javascript-async-await/sources.md b/content/topics/javascript-async-await/sources.md new file mode 100644 index 0000000..ee51324 --- /dev/null +++ b/content/topics/javascript-async-await/sources.md @@ -0,0 +1,8 @@ +# Authoring sources + +- [MDN async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) — returned Promises, synchronous entry, and the await-enabled function body. +- [MDN await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) — accepted inputs, rejection behavior, suspension, and microtask continuations. +- [ECMAScript Await](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#await) — suspension and resumption semantics. +- Local study guide: `study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 5, in the engineering-career repository. + +2026-11-03 revision: the existing ready-value example now awaits the ordinary string '3' and shows 1 → outside → 3. The input table gives that concrete value, and a nearby callout separates unchanged result from deferred continuation. The already-fulfilled-Promise equivalence is retained. No additional timing example or topic-status change is introduced. diff --git a/content/topics/javascript-async-await/topic.md b/content/topics/javascript-async-await/topic.md new file mode 100644 index 0000000..f8f15a3 --- /dev/null +++ b/content/topics/javascript-async-await/topic.md @@ -0,0 +1,64 @@ +--- +id: '8cc54b47-6d86-479d-9c84-e5b702a4b8aa' +title: 'async and await' +status: 'accepted' +summary: 'What async changes, what await accepts, and when execution pauses and resumes.' +iconKey: 'async' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: + - '30f56ccc-ceca-4590-8022-d81a3f3ca796' +relatedTopicIds: + - 'aa0d3bcb-7941-4636-b73c-806293b1d961' + - '33af9431-3a66-49d4-9cc7-87c3273a53bb' +--- + +## What does async change? + +Adding `async` to a function does two things: + +- **Every call returns a Promise.** A returned ordinary value becomes its fulfillment value; an uncaught throw rejects it. Returning another Promise makes it follow that Promise's outcome. +- **Allows `await` inside its body.** + +> Calling an async function **starts its body immediately on the current JS thread**. `async` alone does not schedule the call for later or move its work to another thread. + +## What does await pause? + +`await expression` first **evaluates the expression now**, then suspends **only the current async function** while it waits for the outcome. It **does not block the JS thread**; the caller can continue. + +- **Fulfillment:** the `await` expression produces the fulfilled value. +- **Rejection:** execution resumes by **throwing the rejection reason at the await point**. A surrounding `try`/`catch` can handle it; otherwise the async function's returned Promise rejects. + +## Already ready still means resume later + +```js +async function readValue() { + console.log(1); + const value = await '3'; + console.log(value); + return value; +} + +const result = readValue(); // result is a Promise +console.log('outside'); +// 1 → outside → 3 +``` + +Awaiting an **already fulfilled Promise**, such as `Promise.resolve('3')`, likewise +resumes later. A pending Promise must settle first. + +## What can await accept? + +A **thenable** is an object with a callable `.then` method. + +| Input | Result | +| ------------------------------ | -------------- | +| **Promise** | Value or throw | +| **Thenable** | Value or throw | +| **Ordinary value**, e.g. `'3'` | Same `'3'` | + +> **Awaiting an ordinary value still suspends the current async function.** +> The result is unchanged; execution still resumes later as a microtask. + +`await` is also available at the top level of a JavaScript module; `async` is needed to use it inside a function. diff --git a/content/topics/javascript-async-concurrency/sources.md b/content/topics/javascript-async-concurrency/sources.md new file mode 100644 index 0000000..acf4451 --- /dev/null +++ b/content/topics/javascript-async-concurrency/sources.md @@ -0,0 +1,8 @@ +# Authoring sources + +Retrieval job: choose sequential await, Promise.all, or Promise.allSettled from operation dependencies and required failure behavior. + +- [ECMAScript Await](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#await) — suspension of the current function. +- [ECMAScript Promise.all](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.all) — ordered result values and rejection before other inputs settle; no cancellation step. +- [ECMAScript Promise.allSettled](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.allsettled) — waits for every input and preserves input order with status records. +- [Fetch Standard: abort fetch](https://fetch.spec.whatwg.org/#abort-fetch) — operation-specific cancellation through a signal. diff --git a/content/topics/javascript-async-concurrency/topic.md b/content/topics/javascript-async-concurrency/topic.md new file mode 100644 index 0000000..99c8549 --- /dev/null +++ b/content/topics/javascript-async-concurrency/topic.md @@ -0,0 +1,59 @@ +--- +id: '30f56ccc-ceca-4590-8022-d81a3f3ca796' +title: 'Sequential versus concurrent async work' +status: 'accepted' +summary: 'Choose sequential await, Promise.all, or Promise.allSettled according to dependencies and failure requirements.' +iconKey: 'async' +domains: + - 'javascript' +kind: 'decision-aid' +childTopicIds: [] +relatedTopicIds: + - '473801af-5283-41fe-9010-4ce462907f01' +--- + +| Need | Choose | +| --------------------------------------------------------------------- | ---------------------- | +| Next operation **needs the previous result** | Sequential `await` | +| Independent operations; **all must succeed** | `Promise.all()` | +| Independent operations; **inspect every outcome**, including failures | `Promise.allSettled()` | + +Here, each `get…()` helper **starts a network request** and returns a Promise for its response data. + +## Sequential — dependent requests + +```js +async function loadOrders() { + const user = await getUser(); // Request the user; wait for their data. + return getOrders(user.id); // Then request orders using that user's ID. +} +``` + +`await loadOrders()` receives the orders **after both requests finish**. + +## Concurrent — independent requests + +```js +async function loadCatalog() { + const products = getProducts(); + const categories = getCategories(); // Starts before products finishes. + return Promise.all([products, categories]); +} +``` + +**The function calls start these operations; `Promise.all()` joins their results.** Passing `[getProducts, getCategories]` passes functions—it does not call them. + +**Both requests can be in progress at the same time.** The function calls that start them still run one after the other. + +## What if one fails? + +| Join | Fulfillment value | On an input rejection | +| ---------------------- | ------------------ | ---------------------------------- | +| `Promise.all()` | `[valueA, valueB]` | **Rejects on the first rejection** | +| `Promise.allSettled()` | Outcome records | **Waits for all inputs** | + +An `allSettled` record is `{ status: 'fulfilled', value }` or `{ status: 'rejected', reason }`. + +Both result arrays preserve **input order**, regardless of completion order. `allSettled` stays pending if an input never settles. + +> **`Promise.all()` rejecting does not cancel the other operations.** Cancellation needs support from the operation, such as `fetch` with an `AbortSignal`. diff --git a/content/topics/javascript-event-loop/execution-cycle.svg b/content/topics/javascript-event-loop/execution-cycle.svg new file mode 100644 index 0000000..cbfb9a0 --- /dev/null +++ b/content/topics/javascript-event-loop/execution-cycle.svg @@ -0,0 +1,241 @@ + + Simplified browser event-loop sequence + Run a ready task to completion, run queued microtasks until none remain including newly added ones, then the browser may update the display. Painting is not guaranteed. Continue with more work. Microtask checkpoints also occur at other specified boundaries. + + +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + + + + + + + + + 1. Run a ready task + Run synchronous JS + to completion. + + + 2. Run microtasks + Run until the queue is empty, + including new microtasks. + + + 3. Display may update + The browser may paint; + a paint is not guaranteed. + Then continue with more work. + Simplified sequence; checkpoints also occur at other boundaries. + diff --git a/content/topics/javascript-event-loop/sources.md b/content/topics/javascript-event-loop/sources.md new file mode 100644 index 0000000..8e2a7dd --- /dev/null +++ b/content/topics/javascript-event-loop/sources.md @@ -0,0 +1,12 @@ +# Authoring references + +Retrieval job: identify what is scheduled as a task or microtask and determine the ordinary execution order. Scope: guide section 2 and requested discussion clarifications. The sequence is explicitly simplified; checkpoints can also occur after callback cleanup with an empty JS stack. + +- [HTML event loops and processing model](https://html.spec.whatwg.org/multipage/webappapis.html#event-loops): task sources, task queues, checkpoints, rendering opportunities. +- [MDN microtask guide](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide): draining, enqueue order, queueMicrotask, Promise and observer callbacks. +- Local study guide: `engineering-career/study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 2. + +- [ECMAScript Await operation](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#await): awaits an ordinary native Promise through a continuation reaction. +- [PerformPromiseThen](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-performpromisethen): pending reactions are registered until settlement; already fulfilled Promises enqueue their reactions immediately. + +2026-11-02 revision: compare the same direct async call and then registration in opposite orders, using one already fulfilled native Promise. The queue labels identify [a, b] versus [b, a]; synchronous 1 precedes both. Each case runs separately. A returned-Promise dependency supplies explicit sequencing. Agent-run checks confirm both outputs; the existing topic status is preserved. diff --git a/content/topics/javascript-event-loop/topic.md b/content/topics/javascript-event-loop/topic.md new file mode 100644 index 0000000..0e4df6b --- /dev/null +++ b/content/topics/javascript-event-loop/topic.md @@ -0,0 +1,97 @@ +--- +id: '42c5c1eb-ad74-4a0c-87eb-817949c5cdbf' +title: 'Event loop, tasks, and microtasks' +status: 'accepted' +summary: 'How the browser schedules ready work and drains microtasks.' +iconKey: 'event-loop' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: + - '33af9431-3a66-49d4-9cc7-87c3273a53bb' +relatedTopicIds: [] +--- + +The **event loop** is the host's scheduling mechanism: it coordinates **when ready tasks run** and **when microtasks are drained**. + +## The order to remember + +![Simplified browser sequence: run a ready task to completion, run microtasks until the queue is empty including newly added ones, then the display may update. Painting is not guaranteed. Continue with more work; checkpoints also occur at other boundaries.](execution-cycle.svg) + +## Callback, task, or microtask? + +- **Callback:** **the function** passed to another API. +- **Task:** **host-scheduled work**, such as dispatching a user interaction or invoking a timer callback. +- **Microtask:** work placed in a **separate queue**, such as invoking a Promise handler. It runs **after current synchronous execution finishes, before another task starts**. + +A **timer callback** is the function passed to `setTimeout` or `setInterval`—not the registration call itself. + +## What is a microtask checkpoint? + +A checkpoint is **when the browser drains the microtask queue**. In the ordinary script/callback examples here, this happens after current synchronous execution finishes and the JS stack is empty. + +- Microtasks run in **enqueue order**. +- Microtasks added while draining **run in the same checkpoint**. +- Draining stops **only when the queue is empty**. Continually adding microtasks can **delay other tasks and rendering**. + +Checkpoints also occur at other specified boundaries; they are **not limited to one checkpoint per task**. + +## Common microtask sources + +- **Promise handlers:** `.then()`, `.catch()`, and `.finally()`, once the relevant Promise settles. +- **After `await`:** resuming the async function when the awaited outcome is ready—even if it was already ready. +- **`queueMicrotask(callback)`:** explicitly queues a callback. +- **`MutationObserver`:** delivery of mutation notifications to observer callbacks. + +```js +console.log('start'); +setTimeout(() => console.log('timer'), 0); +Promise.resolve().then(() => console.log('promise')); +console.log('end'); +// start → end → promise → timer +``` + +## `await` or `.then()`: which runs first? + +**Compare when their microtasks are queued.** Run each case separately with this +setup, using an **already fulfilled native Promise**: + +```js +const ready = Promise.resolve(); + +async function somefun() { + console.log(1); + await ready; + console.log('a'); +} +``` + +**Reach `await` first → queue `[a, b]`:** + +```js +somefun(); +ready.then(() => console.log('b')); +// 1 → a → b +``` + +**Register `.then()` first → queue `[b, a]`:** + +```js +ready.then(() => console.log('b')); +somefun(); +// 1 → b → a +``` + +**`1` prints synchronously in both cases.** Calling `.then()` queues its callback; +it does not run it inline. Both `a` and `b` wait until current synchronous execution +finishes. A pending awaited Promise must settle before its continuation is queued. + +To require `b` after `a`, attach the handler to **the function's returned Promise**: +`somefun().then(() => console.log('b'))`. + +## Tasks do not share one global FIFO + +Browsers have multiple task sources and task queues. There is no single global FIFO +ordering every timer, network event, and click. + +**Registration order alone does not guarantee execution order across different task sources.** diff --git a/content/topics/javascript-execution/busy-thread.svg b/content/topics/javascript-execution/busy-thread.svg new file mode 100644 index 0000000..287461c --- /dev/null +++ b/content/topics/javascript-execution/busy-thread.svg @@ -0,0 +1,236 @@ + + Busy JavaScript thread and waiting callbacks + A long synchronous calculation occupies the JavaScript thread. Eligible timer callbacks, click handlers, and network response handlers wait. Networking can still progress outside the JavaScript stack. The examples do not specify callback execution order. + + +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + + + + + + + + + JS thread: busy + Long calculation + Runs to completion + + Waiting callbacks + Timer + Click + Network response + Networking can progress outside the JS stack. + Examples shown; no execution order implied. + diff --git a/content/topics/javascript-execution/sources.md b/content/topics/javascript-execution/sources.md new file mode 100644 index 0000000..8203f1b --- /dev/null +++ b/content/topics/javascript-execution/sources.md @@ -0,0 +1,10 @@ +# Authoring references + +Scope: section 1 of the JavaScript Async Execution and Reactivity guide and Gabriel's requested clarifications. Retrieval job: determine what executes immediately, what the stack tracks, and what the browser manages while JavaScript is busy. Draft; owner acceptance pending. + +- Local guide: `engineering-career/study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 1. +- [MDN execution model](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model): stack, host, threads, run-to-completion. +- [MDN callbacks](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function): callback timing and synchronous array callbacks. +- [HTML timers](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers): timer registration and scheduled tasks. + +No microtasks, Promise semantics, or timer cancellation coverage in this topic. diff --git a/content/topics/javascript-execution/topic.md b/content/topics/javascript-execution/topic.md new file mode 100644 index 0000000..34ad4a4 --- /dev/null +++ b/content/topics/javascript-execution/topic.md @@ -0,0 +1,58 @@ +--- +id: 'b83de364-934a-4b7d-a805-f7d2061d9614' +title: 'Execution: call stack and browser host' +status: 'accepted' +summary: 'When functions and callbacks run, what the call stack tracks, and how the browser manages waiting.' +iconKey: 'execution' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: [] +relatedTopicIds: [] +--- + +> Calling an ordinary function **starts its body immediately**. +> +> Passing a function as a callback **does not call it**. The receiving API determines when it runs. + +## Calls and callbacks + +A **callback** is a function passed elsewhere to be called. The word says nothing about timing. + +| Code | When does `foo` run? | +| ----------------------- | ----------------------------------------------------------- | +| `foo()` | **Immediately** | +| `[1, 2].map(foo)` | **Synchronously**, during `map` | +| `setTimeout(foo, 100)` | **Later**, when eligible and execution can proceed | +| `setInterval(foo, 100)` | **Repeatedly**, as timer callbacks get opportunities to run | + +## Call stack: active calls + +The call stack records **active calls**. Calling a function adds a **frame**; returning removes it and resumes the caller. + +## Browser host: waiting and readiness + +The browser supplies **timers, networking, and DOM events**. + +Calling `setTimeout` or `setInterval` **registers future work** with the host. After registration returns, **the script continues**. + +```js +console.log('start'); +setTimeout(() => console.log('timer'), 100); +console.log('continue'); +// start → continue → timer +``` + +The host manages the wait, then makes the callback eligible to execute. **Eligible does not mean running:** execution can be delayed by other work. + +> A timer is bookkeeping for a future callback—not a function sleeping on the call stack. +> +> **The registration call runs now; the callback runs later.** + +## One thread: run to completion + +Ordinary page JavaScript runs on the **browser's main thread**. Workers have **separate execution threads**. + +**A queued task cannot interrupt JavaScript already executing on that thread.** The current execution runs to completion before another task begins. + +![The JavaScript thread runs a long calculation to completion while timer callbacks, click handlers, and network response handlers wait. Networking can still progress outside the JS stack.](busy-thread.svg) diff --git a/content/topics/javascript-polling/polling-timing.svg b/content/topics/javascript-polling/polling-timing.svg new file mode 100644 index 0000000..528e7d3 --- /dev/null +++ b/content/topics/javascript-polling/polling-timing.svg @@ -0,0 +1,260 @@ + + Overlapping interval requests versus waiting after completion + On one shared time axis, the interval starts three-second requests at zero, one, and two seconds, so they overlap. Completion-based polling runs a request from zero to three seconds, waits one second, then runs the next from four to seven seconds. Times are illustrative, measured from the first request start. + + +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + + + + + + + +Time +0 s + +1 s + +2 s + +3 s + +4 s + +5 s + +6 s + +7 s + +Interval +Every 1 s + +Request 1 + +Request 2 + +Request 3 + +After completion +Wait 1 s + +Request 1 + +1 s wait + +Request 2 +Each request takes 3 s; times are illustrative. + diff --git a/content/topics/javascript-polling/sources.md b/content/topics/javascript-polling/sources.md new file mode 100644 index 0000000..a223046 --- /dev/null +++ b/content/topics/javascript-polling/sources.md @@ -0,0 +1,11 @@ +# Authoring references + +Retrieval job: choose and implement polling that waits for completion before scheduling another operation. Diagram times are illustrative, measured from the first request start; not timer guarantees. Code adapted from the local guide, including its error, stop, and non-settlement caveats. + +- [MDN setInterval: ensure execution is shorter than interval frequency](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#ensure_that_execution_duration_is_shorter_than_interval_frequency): overlapping requests and recursive timeout approach. +- [HTML timers](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers): repetition and cancellation. +- Local study guide: `engineering-career/study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 3. + +- [MDN closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures): nested functions retain access to their outer lexical environment after the outer function returns; separate calls have separate environments. + +2026-11-03 revision: add the start/stop usage and distinguish one-time setup from per-tick refresh. A short shared-state note explains the nesting. Polling implementation, first-tick delay, cancellation limits and accepted status are unchanged. diff --git a/content/topics/javascript-polling/topic.md b/content/topics/javascript-polling/topic.md new file mode 100644 index 0000000..e9fabd4 --- /dev/null +++ b/content/topics/javascript-polling/topic.md @@ -0,0 +1,72 @@ +--- +id: '71f4a102-3d2d-432a-ae2c-67dd7991550f' +title: 'Polling without overlapping requests' +status: 'accepted' +summary: 'Schedule the next timeout after the current operation settles, with explicit stop and timeout policies.' +iconKey: 'concurrency' +domains: + - 'javascript' +kind: 'pattern' +childTopicIds: [] +relatedTopicIds: [] +--- + +**To wait after each operation finishes, schedule the next timeout after `await`.** An interval does not wait for an async callback's Promise. + +## Interval versus completion-based polling + +With a **1-second interval** and a **3-second request**, multiple requests can be outstanding. This is overlapping asynchronous work, not simultaneous JavaScript callbacks. + +![One shared time axis compares three-second requests: the interval starts requests at 0, 1, and 2 seconds, so they overlap. Completion-based polling runs the first request from 0 to 3 seconds, waits 1 second, then runs the second from 4 to 7 seconds. Times are illustrative, measured from the first request start.](polling-timing.svg) + +**Completion-based cadence = operation time + delay + scheduling overhead.** A 3-second operation followed by a 1-second delay gives roughly 4 seconds between starts, not 1 second. + +## Start and stop one poller + +- `startPolling(...)` **sets up one poller** and returns its stop function. +- The nested `tick()` **runs one refresh**, waits for it to settle, then schedules + the next tick—even after a failure. + +`refresh()` must return a Promise covering the **whole operation**. `reportError` must not throw. + +```js +function startPolling(refresh, reportError, delayMs = 1000) { + let stopped = false; + let timerId; + + async function tick() { + try { + await refresh(); + } catch (error) { + reportError(error); + } finally { + if (!stopped) timerId = setTimeout(tick, delayMs); + } + } + + timerId = setTimeout(tick, delayMs); + return () => { + stopped = true; + clearTimeout(timerId); + }; +} +``` + +**Start it, keep the returned function, then call that function to stop:** + +```js +const stop = startPolling(refresh, reportError, 1000); + +// Later: +stop(); +``` + +The nested `tick` and the stop function share this call's `stopped` and `timerId`, +**even after `startPolling` returns**. Each new call creates separate poller state. + +The first tick waits `delayMs`. **One poller does not overlap its `refresh` calls.** + +## Two limits to handle + +- Stopping prevents future ticks. It **does not abort a request already running**; that needs separate cancellation. +- A request that never settles prevents the next tick. Real polling needs an operation-timeout policy. **Timing out the wait does not cancel the underlying request**; abort it as appropriate if overlap must remain impossible. diff --git a/content/topics/javascript-promise-chains/sources.md b/content/topics/javascript-promise-chains/sources.md new file mode 100644 index 0000000..f4ec1e6 --- /dev/null +++ b/content/topics/javascript-promise-chains/sources.md @@ -0,0 +1,10 @@ +# Authoring sources + +Retrieval job: determine what a Promise handler passes downstream and where failure and cleanup are handled. + +- [ECMAScript Promise.prototype.then](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.then) — new derived Promise and reaction propagation. +- [ECMAScript NewPromiseReactionJob](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-newpromisereactionjob) — handler return values and throws determine the derived outcome. +- [ECMAScript Promise.prototype.catch](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.catch) — rejection handler placement. +- [ECMAScript Promise.prototype.finally](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.prototype.finally) — no result argument, outcome preservation, waiting, and failure replacement. + +- [RxJS Observable source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/Observable.ts) — subscribe registers a next handler and returns a Subscription; handler return values do not transform the source. diff --git a/content/topics/javascript-promise-chains/topic.md b/content/topics/javascript-promise-chains/topic.md new file mode 100644 index 0000000..d95a1e3 --- /dev/null +++ b/content/topics/javascript-promise-chains/topic.md @@ -0,0 +1,142 @@ +--- +id: '473801af-5283-41fe-9010-4ce462907f01' +title: 'Promise chains and error handling' +status: 'accepted' +summary: 'What handlers pass downstream, how missing returns break a chain, and where errors and cleanup go.' +iconKey: 'promise' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - '8cc54b47-6d86-479d-9c84-e5b702a4b8aa' +--- + +> `.then()` does two things: **registers a handler** and **returns a new Promise** for that handler's outcome. + +## The Promise exists before its result is ready + +```js +const original = Promise.resolve(7); // Already fulfilled with 7. + +function double(value) { + return value * 2; +} + +const doubled = original.then(double); // New Promise; still pending. +``` + +**`double` is an ordinary function.** Passing it to `.then()` registers it as a Promise handler; it doesn't call it immediately. + +| When | What happens | `original` | `doubled` | +| --------------------- | ------------------------------------------------------ | -------------- | ------------------- | +| Synchronously | `.then()` registers `double` and returns a new Promise | Fulfilled: `7` | **Pending** | +| Later, in a microtask | `double(7)` returns `14`, fulfilling the new Promise | Fulfilled: `7` | **Fulfilled: `14`** | + +**Calling `double(7)` directly would run it synchronously.** + +## Compared with subscribe() + +Both calls register a handler; their return values serve different purposes: + +| Call | Returns | +| ------------------------------- | ------------------------------------- | +| `promise.then(handler)` | **Promise** for the handler's outcome | +| `observable.subscribe(handler)` | **Subscription** for cleanup | + +In `subscribe(handler)`, the handler receives each emitted value. Its return value is ignored; use `pipe(map(...))` to transform Observable values. + +## What reaches the next Promise handler? + +| Handler does… | New Promise… | +| -------------------------------- | ------------------------------ | +| `return value` | Fulfills with `value` | +| `return anotherPromise` | Follows that Promise's outcome | +| `throw error` | Rejects with `error` | +| No returned value, e.g. log only | Fulfills with **`undefined`** | + +### Logging with and without return + +```js +const original = Promise.resolve(7); + +const logged = original.then((value) => { + console.log(value); +}); // logged fulfills with undefined. + +const kept = original.then((value) => { + console.log(value); + return value; +}); // kept fulfills with 7. +``` + +### Skipped callback, new Promise + +```js +const original = Promise.resolve(7); +const afterCatch = original.catch((error) => 0); +const doubled = afterCatch.then((value) => value * 2); +``` + +```text +Fulfilled values +original (7) → afterCatch (7) → doubled (14) +``` + +**`.catch()` returns a new Promise even when its error callback is skipped.** Here, `afterCatch` fulfills with `7`, so the callback passed to **`afterCatch.then(...)`** receives `7`. + +On rejection, `.then(successHandler)` skips that callback and returns a new Promise **rejected with the same error**. + +## Return the next operation + +Here, `getProduct` and `getStock` return Promises: + +```js +getProduct(id) + .then((product) => getStock(product.id)) + .then((stock) => renderStock(stock)) + .catch((error) => showError(error)) + .finally(() => setLoading(false)); +``` + +> **Return the Promise to keep its result and failure in the chain.** +> `product => getStock(product.id)` returns it; `product => { getStock(product.id); }` does not. + +Without that return, the next handler receives `undefined` without waiting for the stock result, and the chain's `.catch()` does not handle a later rejection from that detached operation. + +## Recover or propagate? + +| Rejection handler | Downstream result | +| --------------------------------------- | ---------------------------------------------- | +| `.catch(() => [])` | **Recovery:** fulfillment with `[]` | +| `.catch(error => { throw error; })` | **Propagation:** rejection with the same error | +| `.catch(error => console.error(error))` | Logs, then **fulfills with `undefined`** | + +A `.catch()` covers failures **upstream of its position**, including throws in earlier handlers. A later failure needs a later handler. With `.then(success, failure)`, `failure` does **not** catch a throw from `success` in that same call. + +## Cleanup with finally + +`.finally(cleanup)` runs cleanup after **success or failure**, without passing it a value or error. It returns a **new Promise**; the original Promise stays unchanged. + +| Cleanup does… | New Promise… | +| ------------------------------------- | ---------------------------------- | +| Finishes successfully | Keeps the original value or error | +| Throws, or returns a rejected Promise | Rejects with the **cleanup error** | + +**Returning a value such as `99` does not replace the original result.** If cleanup returns a Promise, the chain waits for it, but ignores its fulfilled value. + +### Catch cleanup failures too + +```js +const original = Promise.resolve(7); + +const afterCleanup = original.finally(() => { + throw new Error('Cleanup failed'); +}); + +afterCleanup.catch((error) => console.log(error.message)); +// Prints 'Cleanup failed'. +// original remains fulfilled with 7. +``` + +Place `.catch()` **after `.finally()`** to handle failures from either the original operation or cleanup. diff --git a/content/topics/javascript-promise-states/sources.md b/content/topics/javascript-promise-states/sources.md new file mode 100644 index 0000000..0d04ab3 --- /dev/null +++ b/content/topics/javascript-promise-states/sources.md @@ -0,0 +1,8 @@ +# Authoring sources + +- [MDN Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — the three states and resolved versus settled. +- [Promise proposal: states and fates](https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md) — resolution as commitment to an outcome. +- [MDN Promise constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) — adoption and ignored subsequent resolving calls. +- Local study guide: `study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 4, in the engineering-career repository. + +2026-11-03 retrieval revision: lead with resolve(value) versus resolve(pendingPromise), distinguish settled states with a compact text flow, replace the saved-resolver example with timer-backed adoption, and separate handler execution in one callout. Resolution includes rejection; no fourth state or guarantee that a handler has run is implied. The timer delay is illustrative. Identity, relationships and accepted status are preserved. diff --git a/content/topics/javascript-promise-states/topic.md b/content/topics/javascript-promise-states/topic.md new file mode 100644 index 0000000..81ad16e --- /dev/null +++ b/content/topics/javascript-promise-states/topic.md @@ -0,0 +1,58 @@ +--- +id: '7d769bdc-1e4e-4a28-b9ea-f5a523dd3fb6' +title: 'Promise states: resolved versus settled' +status: 'accepted' +summary: 'Distinguish a final result from commitment to an outcome, and keep handler execution separate.' +iconKey: 'concurrency' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: [] +relatedTopicIds: [] +--- + +## Two ways to resolve + +| Call | Committed to | State now | +| ------------------------- | --------------------------------- | --------- | +| `resolve(7)` | The value `7` | Fulfilled | +| `resolve(pendingPromise)` | That Promise's value or rejection | Pending | + +**Both are resolved. Only the first is settled.** In the second case, the source +of the answer is fixed, but the answer is not available yet. + +Once resolved, later calls to that Promise's `resolve` or `reject` **cannot redirect +its outcome**. + +## Settled means fulfilled or rejected + +```text +pending + ├─→ fulfilled: value (settled) + └─→ rejected: reason (settled) +``` + +A rejected Promise is also resolved; **resolved does not mean successful**. +A Promise can remain pending indefinitely. Once settled, its value or rejection +reason cannot change. + +## Resolved now, settled later + +```js +const inner = new Promise((resolve) => { + setTimeout(() => resolve(7), 1000); +}); + +const outer = new Promise((resolve) => resolve(inner)); +// Now: outer is resolved, but pending — it must follow inner. + +outer.then((value) => console.log(value)); +// Later: outer fulfills with 7, then its handler logs 7. +``` + +`outer` takes the **value or rejection from `inner`**, rather than treating the +Promise object itself as its final value. If `inner` never settles, `outer` stays +pending. + +> **Neither resolved nor settled means the handlers have run.** A Promise can +> already be fulfilled before you attach `.then()`; its handler runs later. diff --git a/content/topics/javascript-promises/sources.md b/content/topics/javascript-promises/sources.md new file mode 100644 index 0000000..2ffe0e0 --- /dev/null +++ b/content/topics/javascript-promises/sources.md @@ -0,0 +1,12 @@ +# Authoring sources + +- [MDN Promise constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) — executor timing, resolving functions, and deferred handlers. +- [ECMAScript Promise objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-objects) — constructor execution and reaction jobs. +- [HTML microtask queuing](https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queuing) — browser integration of Promise jobs. +- Local study guide: `study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 4, in the engineering-career repository. + +- [ECMAScript Await](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#await) — suspension and later continuation, including for an already fulfilled native Promise. + +2026-11-03 revision: compare the next statement after resolve(7) with the next statement after await Promise.resolve(7). Replace the existing resolve-is-not-return bullet with the comparison to avoid duplication. The timing example and accepted status are preserved. + +- [ECMAScript Promise.resolve](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise.resolve) — resolving an ordinary value and reusing an existing Promise when its constructor matches. diff --git a/content/topics/javascript-promises/topic.md b/content/topics/javascript-promises/topic.md new file mode 100644 index 0000000..196e68e --- /dev/null +++ b/content/topics/javascript-promises/topic.md @@ -0,0 +1,61 @@ +--- +id: 'aa0d3bcb-7941-4636-b73c-806293b1d961' +title: 'Promises: results and callback timing' +status: 'accepted' +summary: 'Distinguish the Promise object, its synchronous executor, and its deferred fulfillment handler.' +iconKey: 'promise' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: + - '7d769bdc-1e4e-4a28-b9ea-f5a523dd3fb6' + - '473801af-5283-41fe-9010-4ce462907f01' +relatedTopicIds: + - '8cc54b47-6d86-479d-9c84-e5b702a4b8aa' + - '42c5c1eb-ad74-4a0c-87eb-817949c5cdbf' +--- + +A Promise represents **one eventual outcome**: **fulfillment** with a value or **rejection** with a reason. + +## Create a Promise from a value + +**For an ordinary value**, these both produce a Promise already fulfilled with `7`: + +```js +Promise.resolve(7); +new Promise((resolve) => resolve(7)); +``` + +**Returning `7` from the executor does not fulfill the Promise**; call `resolve(7)`. + +For an existing native Promise `p`, `Promise.resolve(p)` can return `p` itself. `new Promise(...)` always creates a new object. + +## Object, producer, consumer + +- Promise object: `result` in the example below; **represents the eventual outcome**. +- Executor (producer): the function passed to `new Promise(...)`; **starts the producing work**. +- Fulfillment handler (consumer): the function passed to `.then(...)`; **receives the fulfilled value**. + +`new Promise(...)` calls your executor and **passes it two functions: `resolve` and `reject`**. The executor can call them immediately, or start asynchronous work that calls them later. + +## Executor now; fulfillment handler later + +```js +console.log('begin'); +const result = new Promise((resolve) => { + console.log('executor'); + resolve(7); + console.log('executor continues'); +}); +result.then((value) => console.log('received', value)); +console.log('end'); +// begin → executor → executor continues → end → received 7 +``` + +| Expression | What happens to the next statement? | +| -------------------------- | --------------------------------------------------------------------- | +| `resolve(7)` | **Runs immediately**; the executor does not pause or return. | +| `await Promise.resolve(7)` | **Runs later**; the current async function suspends, even when ready. | + +- **The executor runs synchronously during construction.** Creating a Promise does not move that function to another thread. +- **The native Promise handler runs later.** Its reaction is scheduled as a Promise job, integrated with the browser's **microtask queue**—**even when `.then(...)` is attached to an already fulfilled Promise**. If the Promise is pending, the handler waits for fulfillment first. diff --git a/content/topics/javascript-rendering-and-yielding/sources.md b/content/topics/javascript-rendering-and-yielding/sources.md new file mode 100644 index 0000000..8ea83f1 --- /dev/null +++ b/content/topics/javascript-rendering-and-yielding/sources.md @@ -0,0 +1,8 @@ +# Authoring references + +Retrieval job: determine why a DOM change has not painted and which yielding approach permits other work. Scope is the browser main thread; the example is an ordinary button handler with an already fulfilled Promise. + +- [HTML processing model](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model): checkpoints and rendering opportunities. +- [MDN microtask guide](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide): microtask processing before rendering and starvation. +- [MDN Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers): work on a background thread. +- Local study guide: `engineering-career/study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 2, loading-indicator and starvation examples. diff --git a/content/topics/javascript-rendering-and-yielding/topic.md b/content/topics/javascript-rendering-and-yielding/topic.md new file mode 100644 index 0000000..62f0f26 --- /dev/null +++ b/content/topics/javascript-rendering-and-yielding/topic.md @@ -0,0 +1,40 @@ +--- +id: '33af9431-3a66-49d4-9cc7-87c3273a53bb' +title: 'Rendering and yielding' +status: 'accepted' +summary: 'Why DOM changes may not paint yet, and how to give other work an opportunity.' +iconKey: 'concurrency' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: [] +relatedTopicIds: [] +--- + +**Updating the DOM changes page state. Painting displays pixels.** + +A DOM change **does not force an immediate paint**, and the browser does not necessarily paint after every task. + +## Why a loading message may not appear yet + +In an ordinary button handler: + +```js +async function onClick() { + label.textContent = 'Loading…'; + await Promise.resolve(); + longCalculation(); +} +``` + +**DOM update → microtask continuation → long calculation → possible paint** + +The fulfilled `await` resumes the function as a microtask, **before the browser gets a rendering opportunity**. The calculation can therefore delay displaying the loading message. + +> **`await` does not guarantee a paint.** Awaiting a pending operation that settles in a later task has a different timeline: the browser **may get a rendering opportunity while it is pending**. + +## Giving other work a chance + +- **Split work into later tasks:** creates opportunities for other callbacks and rendering. It does **not guarantee a particular frame**. +- **Consider a worker for substantial CPU work:** moves suitable computation off the main thread. Adding `async` alone does not do this. +- **Use microtasks for short deferred coordination**, not repeatedly yielding a large calculation. The browser drains the queue before proceeding; more microtasks can keep postponing other work. diff --git a/content/topics/javascript-timers/sources.md b/content/topics/javascript-timers/sources.md new file mode 100644 index 0000000..df7e810 --- /dev/null +++ b/content/topics/javascript-timers/sources.md @@ -0,0 +1,7 @@ +# Authoring references + +Retrieval job: distinguish timer eligibility from actual execution and determine cancellation scope. + +- [HTML timers](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers): registration, delay rules, clearing timer IDs, repetition. +- [MDN setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout): reasons for longer delays, background throttling, zero-delay behavior. +- Local study guide: `engineering-career/study-library/generated/javascript-async-execution-and-reactivity/guide.md`, section 3. diff --git a/content/topics/javascript-timers/topic.md b/content/topics/javascript-timers/topic.md new file mode 100644 index 0000000..ccc92b4 --- /dev/null +++ b/content/topics/javascript-timers/topic.md @@ -0,0 +1,43 @@ +--- +id: '52ff9588-9f91-4fa9-9181-2fdb53620d67' +title: 'Timers: delays and cancellation' +status: 'accepted' +summary: 'When timeout callbacks become eligible and what clearing a timer actually cancels.' +iconKey: 'timer' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: + - '71f4a102-3d2d-432a-ae2c-67dd7991550f' +relatedTopicIds: [] +--- + +**A timer delay is a scheduling threshold, not a reservation on the CPU.** Becoming eligible does not guarantee that the callback runs immediately. + +## Zero delay still means later + +```js +setTimeout(() => console.log('timer'), 0); +console.log('now'); +// now → timer +``` + +`0` means later eligibility, **not immediate execution**. Busy JavaScript, queued work, background-tab throttling (browsers delaying timers in inactive tabs to save resources), and browser timer rules can all postpone execution. + +## Cancel future callbacks + +```js +const timerId = setTimeout(showReminder, 500); +clearTimeout(timerId); // Prevent the pending callback. +``` + +Clear obsolete timers when **a component is destroyed** or **newer input supersedes old work**. + +- **`clearTimeout(id)`:** cancel a pending timeout callback. +- **`clearInterval(id)`:** stop future interval callbacks. + +> Clearing a timer **does not undo an executed callback** or **cancel a request it already started**. Cancel that operation separately. + +## Repeated ticks do not await requests + +`setInterval` schedules repeated callbacks. The callbacks execute **one at a time on this JS thread**, but asynchronous operations started by different ticks **can overlap**. For request polling, see the child topic. diff --git a/content/topics/javascript/topic.md b/content/topics/javascript/topic.md index 57bcaee..a388623 100644 --- a/content/topics/javascript/topic.md +++ b/content/topics/javascript/topic.md @@ -2,14 +2,21 @@ id: '32ce80fd-fd5a-4dce-bcb9-b104889a47da' title: 'JavaScript' status: 'accepted' -summary: 'Angular application reference topics.' +summary: 'Language execution, browser scheduling, Promises, async/await, RxJS timing, and Angular application topics.' iconKey: 'javascript' domains: - 'javascript' kind: 'area' childTopicIds: + - 'b83de364-934a-4b7d-a805-f7d2061d9614' + - '42c5c1eb-ad74-4a0c-87eb-817949c5cdbf' + - '52ff9588-9f91-4fa9-9181-2fdb53620d67' + - 'aa0d3bcb-7941-4636-b73c-806293b1d961' + - '8cc54b47-6d86-479d-9c84-e5b702a4b8aa' + - '71cad1e5-9d13-465a-9f62-c1d00b275d95' + - '0be8a4b3-7ad3-4fce-ba10-6bae6bf6d45c' - 'cbbb9857-d3fa-47b8-8b47-d91b3f3dde7f' relatedTopicIds: [] --- -Reference topics for Angular applications. +Reference topics for JavaScript execution, browser scheduling, Promises, async/await, RxJS notification timing, and Angular applications. diff --git a/content/topics/rxjs-notification-timing/sources.md b/content/topics/rxjs-notification-timing/sources.md new file mode 100644 index 0000000..b6cd4ab --- /dev/null +++ b/content/topics/rxjs-notification-timing/sources.md @@ -0,0 +1,9 @@ +# Authoring references + +Retrieval job: determine the execution context of an RxJS notification handler. Verified against locally installed RxJS 7.8.2 source. The Promise row assumes a native Promise, not an arbitrary thenable. No scheduler overrides in the table. + +- [RxJS of](https://rxjs.dev/api/index/function/of): synchronous emission and completion. +- [RxJS innerFrom source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/observable/innerFrom.ts): fromArrayLike and fromPromise call subscriber methods directly. +- [RxJS Subscriber source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/Subscriber.ts): notification delivery. +- [RxJS interval source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/observable/interval.ts): asyncScheduler default. +- [RxJS observeOn](https://rxjs.dev/api/operators/observeOn): scheduler-controlled notification delivery. diff --git a/content/topics/rxjs-notification-timing/topic.md b/content/topics/rxjs-notification-timing/topic.md new file mode 100644 index 0000000..29b0baf --- /dev/null +++ b/content/topics/rxjs-notification-timing/topic.md @@ -0,0 +1,41 @@ +--- +id: '71cad1e5-9d13-465a-9f62-c1d00b275d95' +title: 'RxJS notification timing' +status: 'accepted' +summary: 'When next, error, and complete handlers run depends on the source and scheduling operators.' +iconKey: 'observable' +domains: + - 'javascript' +kind: 'concept' +childTopicIds: [] +relatedTopicIds: [] +--- + +**RxJS handlers do not have a fixed queue.** The source and any scheduling operators determine when `next`, `error`, and `complete` run. + +## Default source timing + +Browser examples, with **no scheduler override or scheduling operator**; `aPromise` is a native Promise. + +| Source | Handler timing | +| ---------------- | --------------------------------- | +| `of(1, 2)` | Immediately, during `subscribe()` | +| `from(aPromise)` | In the Promise's microtask | +| `interval(1000)` | In a timer task | + +`of` emits its values and completes synchronously. `from(aPromise)` emits and completes on fulfillment, or sends `error` on rejection. `interval` emits repeated `next` notifications; it does not complete by itself. + +## Delivery does not add another microtask + +When RxJS delivers a notification, it normally **calls your handler directly** in that execution context. It does **not automatically queue a separate microtask** for the handler. + +```js +console.log('before'); +of(1, 2).subscribe((value) => console.log(value)); +console.log('after'); +// before → 1 → 2 → after +``` + +## Scheduling can change the answer + +Operators such as **`observeOn` reschedule notification delivery** using the supplied scheduler. Check the source and the operator chain before classifying a handler as synchronous, task-based, or microtask-based. diff --git a/content/topics/rxjs-subscriptions-and-cleanup/sources.md b/content/topics/rxjs-subscriptions-and-cleanup/sources.md new file mode 100644 index 0000000..7a95f21 --- /dev/null +++ b/content/topics/rxjs-subscriptions-and-cleanup/sources.md @@ -0,0 +1,11 @@ +# Authoring sources + +Retrieval job: distinguish source termination from consumer unsubscription and decide who owns subscription cleanup. Checked against the locally installed RxJS 7.8.2 implementation. + +- [RxJS Observable guide](https://rxjs.dev/guide/observable) — subscribing and disposing execution; cold versus shared/hot sources. +- [RxJS Observable source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/Observable.ts) — subscriber setup and registering returned teardown. +- [RxJS Subscriber source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/Subscriber.ts) — complete/error call unsubscribe; unsubscribe does not deliver a complete notification. +- [RxJS Subscription source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/Subscription.ts) — disposal of registered resources. +- [RxJS finalize source, 7.8.2](https://github.com/ReactiveX/rxjs/blob/7.8.2/src/internal/operators/finalize.ts) — finalizer on complete, error, and explicit unsubscribe. +- [Angular: making HTTP requests](https://angular.dev/guide/http/making-requests#http-observables) — requests start per subscription, usual completion, abort on unsubscribe, and interceptors. +- [Angular: RxJS interop](https://angular.dev/ecosystem/rxjs-interop) — default automatic toSignal destruction cleanup and takeUntilDestroyed. The topic describes defaults, without manualCleanup or a custom lifetime. diff --git a/content/topics/rxjs-subscriptions-and-cleanup/topic.md b/content/topics/rxjs-subscriptions-and-cleanup/topic.md new file mode 100644 index 0000000..e9a92fc --- /dev/null +++ b/content/topics/rxjs-subscriptions-and-cleanup/topic.md @@ -0,0 +1,59 @@ +--- +id: '0be8a4b3-7ad3-4fce-ba10-6bae6bf6d45c' +title: 'Observable subscriptions and cleanup' +status: 'accepted' +summary: 'What subscribing starts, how completion differs from unsubscription, and when cleanup is needed.' +iconKey: 'observable' +domains: + - 'javascript' +kind: 'operations' +childTopicIds: [] +relatedTopicIds: + - '71cad1e5-9d13-465a-9f62-c1d00b275d95' +--- + +**An Observable is the source you subscribe to; a Subscription is the handle you can unsubscribe.** + +## What does subscribe start? + +| Source | Each `subscribe()`… | +| ------------------------------- | ------------------------------------------------------------ | +| Cold, e.g. Angular `HttpClient` | Starts a **separate execution/request** | +| Shared/hot, e.g. a `Subject` | Attaches a receiver; the producer may **already be running** | + +Creating an Observable does not guarantee that underlying work waits for subscription: `from(fetch(url))` wraps a request **already started by `fetch(url)`**. + +## Complete, error, or unsubscribe? + +| Subscription ends by… | Observer callback | Registered teardown | +| --------------------- | ----------------- | ------------------- | +| Source completes | `complete()` | Runs | +| Source fails | `error(reason)` | Runs | +| Consumer unsubscribes | **Neither** | Runs | + +Afterward, that subscription receives no further notifications. **When a subscription ends, RxJS also runs any cleanup provided by the source**—for example, stopping an interval's timer or removing a DOM event listener. + +## Cleanup on every exit + +**Put your cleanup callback in `finalize()` if it must run whether the source completes, fails, or you unsubscribe.** A `complete` handler does not run on error or unsubscription. + +```js +const subscription = interval(1000) + .pipe(finalize(() => console.log('cleanup'))) + .subscribe({ + next: (value) => console.log(value), + complete: () => console.log('complete'), + }); + +subscription.unsubscribe(); +// cleanup — no ticks, and no 'complete' callback. +``` + +**Unsubscribing stops this subscription.** Whether it stops the producer depends on the source and its teardown. A shared producer can continue for other subscribers; wrapping a Promise does not make that Promise cancellable. + +## Do HTTP subscriptions need destruction cleanup? + +- **Once the request completes or errors:** its subscription closes automatically. There is no ongoing subscription left to unsubscribe; interceptors can affect completion. +- **If the component disappears first:** destruction cleanup can prevent stale handlers and abort an in-progress Angular HTTP request. It cannot undo server changes already made. + +In Angular, the `async` pipe and `toSignal()` manage their subscriptions automatically. For a manual component subscription, `takeUntilDestroyed()` ties its lifetime to the component; use it for subscriptions that should end when the component is destroyed. diff --git a/contracts/runtime-catalog.ts b/contracts/runtime-catalog.ts index 0f36a12..c1b4fed 100644 --- a/contracts/runtime-catalog.ts +++ b/contracts/runtime-catalog.ts @@ -1,6 +1,13 @@ export const TOPIC_ICON_KEYS = [ 'java', 'javascript', + 'angular', + 'execution', + 'event-loop', + 'timer', + 'promise', + 'async', + 'observable', 'architecture', 'algorithm', 'database', diff --git a/docs/content-storage.md b/docs/content-storage.md index ab76ac7..76ac42a 100644 --- a/docs/content-storage.md +++ b/docs/content-storage.md @@ -141,7 +141,9 @@ Two presentation properties are optional for a Topic generally: registry key rather than a filename, URL, or markup fragment. When omitted, the UI supplies its generic icon fallback. -The supported icon keys are `java`, `javascript`, `architecture`, `algorithm`, `database`, +The supported icon keys are `java`, `javascript`, `angular`, `execution`, +`event-loop`, `timer`, `promise`, `async`, `observable`, `architecture`, `algorithm`, +`database`, `array`, `collection`, `conversion`, `copy`, `creation`, `deque`, `heap`, `list`, `map`, `operations`, `priority`, `queue`, `set`, `complexity`, `concurrency`, `equality`, `ordering`, `persistence`, `network`, `tradeoff`, and `validation`. Topics may @@ -155,11 +157,20 @@ The subject-specific keys provide distinct recognition within a technical domain | `network` | Connected components | System architecture | | `tradeoff` | Balance scales | Trade-off decisions | | `validation` | Checklist | Validation rules | - -These assets use the selected Lucide 1.17.0 glyphs with the application's stroke +| `execution` | Layers | Call stack and execution | +| `event-loop` | Loop arrows | Event-loop processing | +| `timer` | Timer | Delays and scheduling | +| `promise` | Checked package | Eventual result | +| `async` | Pause | Suspension and resumption | +| `observable` | Broadcast | Emitted notifications | +| `angular` | Angular logo | Angular framework | + +The subject glyphs use selected Lucide 1.17.0 icons with the application's stroke width and accent colors. Their license notice ships alongside them at `public/icons/topics/lucide-LICENSE.txt`; the renderer loads local SVGs without a -runtime icon-library dependency. +runtime icon-library dependency. Angular uses its official gradient logo from +the Angular repository, with attribution and CC BY 4.0 license information in +`public/icons/topics/angular-LICENSE.txt`. The supported domain keys, in canonical generated and display order, are `java`, `collections`, `concurrency`, `persistence`, `databases`, `http`, diff --git a/docs/visual-design.md b/docs/visual-design.md index 1aebbc6..ef2e4f2 100644 --- a/docs/visual-design.md +++ b/docs/visual-design.md @@ -88,6 +88,10 @@ The network symbol provides a reusable architecture cue; the checklist symbol identifies validation rules. Topic icons remain semantic catalog keys rather than title- or hierarchy-specific renderer choices. +JavaScript's execution, event-loop, timer, Promise, async/await, and RxJS Topics +use distinct green layers, loop arrows, timer, checked-package, pause, and broadcast +symbols. Angular uses its official gradient logo on the same soft green surface. + ### Typography Typography supplies much of the interface's hierarchy: diff --git a/public/icons/topics/angular-LICENSE.txt b/public/icons/topics/angular-LICENSE.txt new file mode 100644 index 0000000..4f47679 --- /dev/null +++ b/public/icons/topics/angular-LICENSE.txt @@ -0,0 +1,10 @@ +Angular logo + +Copyright Google LLC. +Source: https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/tutorials/common/src/assets/angular.svg +Brand and license information: https://angular.dev/press-kit +License: Creative Commons Attribution 4.0 International (CC BY 4.0) +https://creativecommons.org/licenses/by/4.0/ + +The original logo geometry and gradient are preserved. An outer 24-by-24 +viewBox adapts the asset to the application icon system. diff --git a/public/icons/topics/angular.svg b/public/icons/topics/angular.svg new file mode 100644 index 0000000..ea154e8 --- /dev/null +++ b/public/icons/topics/angular.svg @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/icons/topics/async.svg b/public/icons/topics/async.svg new file mode 100644 index 0000000..a850728 --- /dev/null +++ b/public/icons/topics/async.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/public/icons/topics/event-loop.svg b/public/icons/topics/event-loop.svg new file mode 100644 index 0000000..b5e65fe --- /dev/null +++ b/public/icons/topics/event-loop.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/public/icons/topics/execution.svg b/public/icons/topics/execution.svg new file mode 100644 index 0000000..bafa085 --- /dev/null +++ b/public/icons/topics/execution.svg @@ -0,0 +1,20 @@ + + + + + + + diff --git a/public/icons/topics/observable.svg b/public/icons/topics/observable.svg new file mode 100644 index 0000000..df54841 --- /dev/null +++ b/public/icons/topics/observable.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/public/icons/topics/promise.svg b/public/icons/topics/promise.svg new file mode 100644 index 0000000..5df52a8 --- /dev/null +++ b/public/icons/topics/promise.svg @@ -0,0 +1,22 @@ + + + + + + + + + diff --git a/public/icons/topics/timer.svg b/public/icons/topics/timer.svg new file mode 100644 index 0000000..1385f8c --- /dev/null +++ b/public/icons/topics/timer.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/src/app/browse/topic-index-page.spec.ts b/src/app/browse/topic-index-page.spec.ts index f29bf1f..6695dd5 100644 --- a/src/app/browse/topic-index-page.spec.ts +++ b/src/app/browse/topic-index-page.spec.ts @@ -39,7 +39,7 @@ describe('TopicIndexPage', () => { host.querySelectorAll('.domain-hierarchy__root > .domain-hierarchy__item app-topic-icon'), ).map((icon) => icon.getAttribute('data-icon-key')), ).toEqual(['java', 'architecture', 'architecture', 'database', 'architecture', 'javascript']); - expect(host.querySelector('[role="status"]')?.textContent).toContain('122 topics'); + expect(host.querySelector('[role="status"]')?.textContent).toContain('134 topics'); }); it('renders the default System Design view as an expandable hierarchy', async () => { diff --git a/src/app/catalog/catalog.service.spec.ts b/src/app/catalog/catalog.service.spec.ts index 7f62fe4..f90980c 100644 --- a/src/app/catalog/catalog.service.spec.ts +++ b/src/app/catalog/catalog.service.spec.ts @@ -219,7 +219,7 @@ describe('CatalogService', () => { const view = service.getTopicBrowseView({ query: '', domain: null, kind: null, status: null }); expect(view.mode).toBe('hierarchy'); - expect(view.resultCount).toBe(122); + expect(view.resultCount).toBe(134); expect(view.sections).toEqual([]); expect(view.hierarchyRoots.map(({ title }) => title)).toEqual([ 'Java', diff --git a/src/app/ui/topic-icon/topic-icon.css b/src/app/ui/topic-icon/topic-icon.css index 36c5f6f..d2d1002 100644 --- a/src/app/ui/topic-icon/topic-icon.css +++ b/src/app/ui/topic-icon/topic-icon.css @@ -21,6 +21,13 @@ img { :host([data-icon-key='architecture']), :host([data-icon-key='concurrency']), +:host([data-icon-key='angular']), +:host([data-icon-key='execution']), +:host([data-icon-key='event-loop']), +:host([data-icon-key='timer']), +:host([data-icon-key='promise']), +:host([data-icon-key='async']), +:host([data-icon-key='observable']), :host([data-icon-key='network']) { --topic-icon-background: var(--color-accent-forest-soft); --topic-icon-color: var(--color-accent-forest);