<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Peter Seliger on Medium]]></title>
        <description><![CDATA[Stories by Peter Seliger on Medium]]></description>
        <link>https://medium.com/@peter-seliger?source=rss-c92e3619bf84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kD1U6Ln8XCE_HOHZVPo0AA.png</url>
            <title>Stories by Peter Seliger on Medium</title>
            <link>https://medium.com/@peter-seliger?source=rss-c92e3619bf84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:39:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peter-seliger/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[“Abortable Promise” Utility Functions]]></title>
            <link>https://peter-seliger.medium.com/abortable-promise-utility-functions-2f05dbce5c72?source=rss-c92e3619bf84------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f05dbce5c72</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <category><![CDATA[abortcontroller]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Peter Seliger]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 12:20:26 GMT</pubDate>
            <atom:updated>2025-09-10T10:55:34.765Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTyXpKoFVMj2L16NaItfFg.jpeg" /><figcaption>Depiction of an “Abortable Promise” generated by DALL-E</figcaption></figure><p>Written in response to <a href="https://medium.com/readers-club/how-to-cancel-a-javascript-promise-that-has-already-started-588fc53e4ee7">“How to cancel a JavaScript promise that has already started”</a>.</p><p>How about coming up with an implementation for an <em>“Abortable Promise”</em> (unless it is settled) where the API layer does abstract away possible traps that one might trip into when following the OP’s example code?</p><p>Based on a possible implementation such as e.g. Promise.withAbort, the original article’s latter example for instance could be simplified to something as straightforward as ...</p><pre>function longRunningTask(resolve, reject, abort, signal) {<br>  console.log(&#39;Time-consuming task started...&#39;);<br><br>  setTimeout(resolve, 5_000, &#39;Success!&#39;);<br><br>  // - `reject` as well, if needed.<br>  // - auto-`abort`, if necessary.<br>  // - utilize `signal` as it seems fit.<br>}<br>const { promise, resolve, reject, abort, signal } = Promise.withAbort();<br><br>signal.addEventListener(&#39;abort&#39;, evt =&gt;<br>  // e.g. the one-time cleanup-task.<br>  console.log(&#39;Time-consuming task aborted ...&#39;, { evt }), {<br>    once: true<br>  }<br>);<br>promise<br>  .then(result =&gt; console.log(&#39;Time-consuming task fulfilled!&#39;))<br>  .catch(reason =&gt;<br>    // covers both `reject` and `abort`.<br>    console.log(&#39;Time-consuming task rejected ...&#39;, { reason })<br>  );<br><br>// cancel/abort the pending long running task after 2 seconds.<br>setTimeout(abort, 2_000, new DOMException(<br>  &#39;Exceeded pending threshold.&#39;, &#39;AbortError&#39;<br>));<br><br>// trigger/start the long running task.<br>longRunningTask(resolve, reject, abort, signal);</pre><p>… in comparison to its former version …</p><pre>function LongRunningTask(signal) {<br>  return new Promise((resolve, reject) =&gt; {<br>    // If the signal is aborted before the task starts, reject directly<br>    if (signal.aborted) {<br>      return reject(new DOMException(&#39;Task aborted&#39;, &#39;AbortError&#39;));<br>    }<br><br>    console.log(&#39;Time-consuming task started...&#39;);<br><br>    const timeoutId = setTimeout(() =&gt; {<br>      console.log(&#39;Time-consuming task completed!&#39;);<br>      resolve(&#39;Success!&#39;);<br>    }, 5000);<br><br>    // Listen for the abort event for cleanup<br>    signal.addEventListener(&#39;abort&#39;, () =&gt; {<br>      clearTimeout(timeoutId); // Clear the timer to actually abort the operation<br>      console.log(&#39;Timer cleared, task aborted.&#39;);<br>      reject(new DOMException(&#39;Task aborted&#39;, &#39;AbortError&#39;));<br>    });<br>  });<br>}<br><br>// --- Usage Example ---<br>const controller = new AbortController();<br><br>LongRunningTask(controller.signal)<br>  .then(console.log)<br>  .catch((err) =&gt; {<br>    if (err.name === &#39;AbortError&#39;) {<br>      console.log(&#39;AbortError caught, task successfully canceled.&#39;);<br>    }<br>  });<br><br>// Cancel the task after 2 seconds<br>setTimeout(() =&gt; {<br>  controller.abort();<br>}, 2000);</pre><p>The Promise.withAbort abstraction liberates one from implementing the bug and race-condition free abort-handling separately and repetitively for every given custom abortable task.<br>As for the OP’s above example code, I would add the promise rejecting abort listener immediately after the LongRunningTask‘s clause that catches signal.aborted; however an implemented Promise.withAbort API already deals with that through code which sits behind its provided abort resolver.</p><p>Other obstacle are the <strong>memory-safe, non-leaking handling of </strong><strong>abort related timeouts and handlers</strong> and the correct <strong>abortion of exclusively pending promises</strong>. Any promise’s resolver function like resolve, reject and abort has to become a <strong>no-op in the very moment this promise settles</strong>.</p><p>An <em>“Abortable Promise”</em> API has to take care of that as well. And it might not only provide a single additional static utility method like the already introduced Promise.withAbort (similar to Promise.withResolvers), but it might provide a pendant to new Promise(define) too; for instance another static method like Promise.abortable(define).</p><p>The next provided code does achieve all of the above mentioned goals …</p><pre>/**<br> * This callback is the custom provided executor-function<br> * which gets all of an abortable promise&#39;s specific resolver<br> * functions and its abort signal passed into.<br> * This callback defines how the created promise does settle.<br> *<br> * @callback abortablePromiseExecutor<br> *  @param {(value?: any) =&gt; void} resolve<br> *   Does resolve its promise with a result.<br> *  @param {(reason?: any) =&gt; void} reject<br> *   Does reject its promise with a reason.<br> *  @param {(reason?: any) =&gt; void} abort<br> *   Does abort its promise with a reason.<br> *  @param {AbortSignal} signal<br> *   Enables listening to its promise&#39;s `abort` event.<br> */<br><br>/**<br> * An object which features all of an abortable promise&#39;s resolver<br> * functions, its abort signal and the abortable promise itself.<br> *<br> * @typedef {Object} AbortablePromiseWithResolversAndSignal<br> *  @property {Promise} promise<br> *   The abortable promise itself.<br> *  @property {(value?: any) =&gt; void} resolve<br> *   Does resolve its promise with a result.<br> *  @property  {(reason?: any) =&gt; void} reject<br> *   Does reject its promise with a reason.<br> *  @property {(reason?: any) =&gt; void} abort<br> *   Does abort its promise with a reason.<br> *  @property {AbortSignal} signal<br> *   Enables listening to its promise&#39;s `abort` event.<br> */<br><br>class AsyncAbortableExecuteError extends Error {<br>  constructor(cause) {<br>    super(<br>      &#39;The custom provided callback does throw. Please check the `cause`.&#39;,<br>      { cause }<br>    );<br>    this.name = &#39;AsyncAbortableExecuteError&#39;;<br>  }<br>}<br>class AsyncAbortError extends Error {<br>  constructor(message, options) {<br>    message = String(message ?? &#39;&#39;).trim() || &#39;Pending async task aborted.&#39;;<br>    options = options ?? {};<br><br>    super(<br>      message,<br>      (Object.hasOwn(options, &#39;cause&#39;) &amp;&amp; { cause: options.cause }) || void 0<br>    );<br>    this.name = &#39;AsyncAbortError&#39;;<br>  }<br>}<br><br>function handleAsyncAbort({ currentTarget: signal }) {<br>  const { reject, state } = this;<br><br>  // guard.<br>  if (state.pending) {<br>    const { reason } = signal;<br><br>    const abortError =<br>      (Error.isError(reason) &amp;&amp; reason.name === &#39;AbortError&#39; &amp;&amp; reason) ||<br>      new AsyncAbortError(null, { cause: reason });<br><br>    if (!abortError.message || !String(abortError.message).trim()) {<br>      abortError.message = &#39;Pending async task aborted.&#39;;<br>    }<br>    // - `reject` is going to take care of removing<br>    //   the bound version of this handler-function<br>    //   from the related internal abort-controller.<br>    reject(abortError);<br>  }<br>}<br><br>/**<br> * Core functionality which defines and manages state<br> * and control-flow of an abortable promise, be it a<br> * promise defined by a custom executor-callback, or<br> * a promise with resolvers.<br> *<br> * @param {abortablePromiseExecutor} [executeCustom]<br> *  A custom provided callback which defines how the<br> *  created promise settles.<br> * @returns {Promise|AbortablePromiseWithResolversAndSignal}<br> */<br>function defineAsyncAbortable(executeCustom) {<br>  const { promise, resolve, reject } = Promise.withResolvers();<br><br>  const asyncState = {<br>    fulfilled: false,<br>    rejected: false,<br>    aborted: false,<br>    pending: true,<br>  };<br>  const listenerController = new AbortController();<br>  const abortController = new AbortController();<br>  const abortSignal = abortController.signal;<br><br>  const resolvePromise = ((proceed, state, controller) =&gt;<br>    // create and return a concise generic `resolve` resolver.<br>    ({<br>      resolve(value) {<br>        // guard.<br>        if (state.pending) {<br>          state.pending = false;<br>          state.fulfilled = true;<br><br>          // listener controller.<br>          controller.abort();<br><br>          proceed(value);<br>        }<br>      },<br>    }[&#39;resolve&#39;]))(resolve, asyncState, listenerController);<br><br>  const rejectPromise = ((proceed, state, controller) =&gt;<br>    // create and return a concise generic `reject` resolver.<br>    ({<br>      reject(reason) {<br>        // guard.<br>        if (state.pending) {<br>          state.pending = false;<br>          state.rejected = true;<br><br>          // listener controller.<br>          controller.abort();<br><br>          proceed(reason);<br>        }<br>      },<br>    }[&#39;reject&#39;]))(reject, asyncState, listenerController);<br><br>  const abortPromise = ((state, controller) =&gt;<br>    // create and return a concise generic `abort` resolver.<br>    ({<br>      abort(reason) {<br>        // guard.<br>        if (state.pending &amp;&amp; !state.aborted) {<br>          state.aborted = true;<br><br>          // abort controller.<br>          controller.abort(reason);<br>        }<br>      },<br>    }[&#39;abort&#39;]))(asyncState, abortController);<br><br>  const abortHandler = handleAsyncAbort.bind({<br>    reject: rejectPromise,<br>    state: asyncState,<br>  });<br>  abortSignal.addEventListener(&#39;abort&#39;, abortHandler, {<br>    signal: listenerController.signal,<br>  });<br>  let result;<br><br>  if (executeCustom) {<br>    try {<br>      executeCustom(resolvePromise, rejectPromise, abortPromise, abortSignal);<br>    } catch (exception) {<br>      rejectPromise(new AsyncAbortableExecuteError(exception));<br>    }<br>    // abortable ... {Promise}<br>    result = promise;<br>  } else {<br>    // with abort ... {AbortablePromiseWithResolversAndSignal}<br>    result = {<br>      promise,<br>      resolve: resolvePromise,<br>      reject: rejectPromise,<br>      abort: abortPromise,<br>      signal: abortSignal,<br>    };<br>  }<br>  return result;<br>}<br><br>/**<br> * `Promise.abortable(executor)`<br> *<br> * Creates an abortable promise; the custom provided executor-callback<br> * ... `executeCustom(resolve, reject, abort, signal)` ... defines how<br> * such a promise is going to settle.<br> *<br> * @param {abortablePromiseExecutor} executeCustom<br> *  A custom provided callback which defines how the created promise<br> *  settles.<br> */<br>function abortable(executeCustom) {<br>  if (typeof executeCustom !== &#39;function&#39;) {<br>    throw new TypeError(<br>      &#39;The single mandatory argument must be a function type.&#39;<br>    );<br>  }<br>  return defineAsyncAbortable(executeCustom);<br>}<br><br>/**<br> * `Promise.withAbort()``<br> *<br> * Returns `{ promise, resolve, reject, abort, signal }` so one<br> * can wire an abortable promise without an executor-callback.<br> *<br> * @returns {AbortablePromiseWithResolversAndSignal}<br> */<br>function withAbort() {<br>  return defineAsyncAbortable();<br>}<br><br>const descriptorOptions = {<br>  enumerable: false, writable: false, configurable: true,<br>};<br><br>// apply minifier safe function names.<br>Object.defineProperty(abortable, &#39;name&#39;, {<br>  ...descriptorOptions, value: &#39;abortable&#39;,<br>});<br>Object.defineProperty(withAbort, &#39;name&#39;, {<br>  ...descriptorOptions, value: &#39;withAbort&#39;,<br>});<br><br>// introduce two new static `Promise` methods.<br>Object.defineProperty(Promise, &#39;abortable&#39;, {<br>  ...descriptorOptions, value: abortable,<br>});<br>Object.defineProperty(Promise, &#39;withAbort&#39;, {<br>  ...descriptorOptions, value: withAbort,<br>});</pre><p>Usage examples, in addition to the very first provided one, which prove the correct implementation of both Promise.abortable and Promise.withAbort are …</p><pre>/*<br> *  test case 1 ... `Promise.abortable`<br> */<br>const aborted = Promise.abortable((resolve, reject, abort/*, signal*/) =&gt; {<br>  setTimeout(resolve, 300, &#39;smoothly fulfilled&#39;);<br>  setTimeout(reject, 200, &#39;plainly rejected&#39;);<br>  setTimeout(abort, 100, &#39;too long pending task&#39;); // &lt;==<br>});<br>const rejected = Promise.abortable((resolve, reject, abort/*, signal*/) =&gt; {<br>  setTimeout(resolve, 200, &#39;smoothly fulfilled&#39;);<br>  setTimeout(reject, 100, &#39;plainly rejected&#39;);     // &lt;==<br>  setTimeout(abort, 300, &#39;too long pending task&#39;);<br>});<br>const fulfilled = Promise.abortable((resolve, reject, abort/*, signal*/) =&gt; {<br>  setTimeout(resolve, 100, &#39;smoothly fulfilled&#39;);  // &lt;==<br>  setTimeout(reject, 100, &#39;plainly rejected&#39;);<br>  setTimeout(abort, 100, &#39;too long pending task&#39;);<br>});<br>setTimeout(() =&gt; console.log({ aborted, rejected, fulfilled }), 200);<br><br>/*<br> *  test case 2 ... `Promise.withAbort`<br> */<br>async function safeAsyncResult(future, ...args) {<br>  let error = null;<br>  let value;<br><br>  // roughly implemented in order to mainly cover the test scenario.<br>  const promise = typeof future === &#39;function&#39; ? future(...args) : future;<br><br>  try {<br>    value = await promise;<br>  } catch (exception) {<br>    error = exception;<br>  }<br>  // safe result tuple.<br>  return [error, value];<br>}<br>function getRandomNonZeroPositiveInteger(maxInt) {<br>  return Math.ceil(Math.random() * Math.abs(parseInt(maxInt, 10)));<br>}<br><br>async function createAbortableRandomlySettlingPromise() {<br>  const { promise, resolve, reject, abort, signal } = Promise.withAbort();<br><br>  // list of values of either ... 300, 400, 500.<br>  const randomDelayList = [<br>    200 + getRandomNonZeroPositiveInteger(3) * 100,<br>    200 + getRandomNonZeroPositiveInteger(3) * 100,<br>    200 + getRandomNonZeroPositiveInteger(3) * 100,<br>  ];<br>  //debugger;<br>  setTimeout(resolve, randomDelayList.at(0), &#39;resolved with value &quot;foo&quot;.&#39;);<br>  setTimeout(reject, randomDelayList.at(1), &#39;rejected with reason &quot;bar&quot;.&#39;);<br>  setTimeout(abort, randomDelayList.at(2), &#39;running for too long&#39;);<br><br>  return promise;<br>}<br><br>const resultList = await Promise.allSettled(<br>  Array.from({ length: 9 }, () =&gt;<br>    safeAsyncResult(createAbortableRandomlySettlingPromise)<br>  )<br>);<br>const safeResultList = resultList.map(({ value }) =&gt; value);<br><br>console.log({ safeResultList });</pre><h3>Final Reasoning</h3><p>Helper functions like the shown Promise.abortable and Promise.withAbort are sufficient as tiny abstraction layers. There is no practical gain in implementing a subclassed AbortablePromise that extends JavaScript’s built-in Promise. On the contrary, going down that route opens a new set of questions: should there be a prototypal abort method on instances; how does one shape an unmistakably safe API for <em>only</em> abortable promises (or a mixed world of regular and abortable promises)? Since there is no clean answer that improves on the helper approach, one would eventually end up with an AbortablePromise whose then and catch still return regular promises. Abort handling would still live in a dedicated abort resolver, and &#39;abort&#39; listening would still rely on each promise’s linked AbortSignal. In other words: stick to regular promises and the utility methods introduced above.</p><h3>Takeaways</h3><ul><li><strong>Helpers beat subclasses.</strong> Tiny, explicit helpers (Promise.abortable, Promise.withAbort) give one predictable cancellation without changing how promises chain or how await behaves.</li><li><strong>Abort ⇒ rejection (by design).</strong> Aborting maps to a rejection (e.g., AsyncAbortError), while an internal aborted flag captures intent for diagnostics.</li><li><strong>Clear contract.</strong> Every executor gets the same quartet: (resolve, reject, abort, signal). Cleanup is automatic; listeners are removed on first settlement.</li><li><strong>Strict invariants.</strong> Exactly-once settlement; abort is idempotent; settled state is immutable; signal.reason tunnels into the rejection cause.</li><li><strong>Races made visible.</strong> Equal-delay examples are intentional: they expose real-world race behavior while guards ensure no double-settlement.</li><li><strong>Interop-friendly.</strong> Plain promises are returned, so await, all, race, and ecosystem libraries behave normally. No species tricks, no subclass surprise.</li><li><strong>Composable with existing APIs.</strong> The AbortSignal plugs straight into fetch, timers, and any userland task that supports cancellation hooks.</li><li><strong>Easy to test.</strong> The design invites small assertions (cleanup, idempotency, race ordering), making correctness demonstrable, not assumed.</li><li><strong>Ergonomics first.</strong> One keeps the mental model of regular promises and adds just enough surface to make cancellation explicit and safe.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f05dbce5c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How breaking from and continuing with JavaScript’s Array::forEach method actually had to look and…]]></title>
            <link>https://peter-seliger.medium.com/how-breaking-from-and-continuing-with-javascripts-array-foreach-method-actually-had-to-look-and-44b445d1bc83?source=rss-c92e3619bf84------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b445d1bc83</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming-concepts]]></category>
            <category><![CDATA[foreach-method]]></category>
            <category><![CDATA[class-constructor]]></category>
            <category><![CDATA[signal]]></category>
            <dc:creator><![CDATA[Peter Seliger]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 15:10:51 GMT</pubDate>
            <atom:updated>2026-01-14T17:12:25.854Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3><strong>How breaking from and continuing with JavaScript’s Array::forEach method actually had to look and to be implemented like.</strong></h3><figure><img alt="AI generated image — Adobe Firefly :: break from and continue with a loop" src="https://cdn-images-1.medium.com/max/1024/1*lDIXuaE3_s5x5n48tGGeyA.jpeg" /><figcaption>AI generated image — Adobe Firefly :: break from and continue with a loop</figcaption></figure><p>1st things first, despite being discussed and promoted otherwise at experts forums and by online articles, there is not a single clean approach/solution to break from the current execution of a <strong><em>forEach</em></strong> method. Every answer except <em>“throw from within the method’s repetitive invoked callback function”</em> is simply false. Any other claim than the latter just shows a lack of understanding of how array iterating methods are working/implemented; and the throwing approach is as much real bad coding practice as is the mutation of the processed array by setting its length property to zero.</p><p>In addition, array methods are neither thought to be interrupted nor to be continued; they implement very specific use cases, of how to handle an array-item during a full array iterating cycle via the provided callback function. This approach, a specialized array-method which invokes a function for each array-item, makes code more readable, better maintainable and enables code reuse since callback functions need to be implemented just once.</p><p>Nobody prevents one from continuing using loops like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await...of</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a>. Always pick the tool which fits the use case best. Never blame its wrong usage on the tool.</p><p><strong><em>Thus, since especially at various medium related channels this topic almost always never gets handled correctly, the next provided paragraphs, by explanation and example code, aim to clarify the very matter once and for all.</em></strong></p><p>Note that the intention of this article is not the promotion of utilizing the provided example code. The focus is educational; approach and implemented code are thought to raise the awareness of what’s actually possible to achieve with the currently available language features.</p><p>Since the language core not just since lately has much more features than at the start of this millennium, one quite easily can implement a prototypal array method which not only enables a break but also a continue command, similar to both statements <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a>.</p><p>In order to achieve the implementation of the iterating array method, one first needs to write some abstractions which do borrow the basic idea from <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController/AbortController">AbortController</a> and its related <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal">AbortSignal</a>.</p><p>Thus, one would implement e.g. a PausedStateSignal ...</p><pre>class PausedStateSignal extends EventTarget {<br>  // shared protected/private state.<br>  #state;<br><br>  constructor(connect) {<br>    super();<br><br>    this.#state = {<br>      isPaused: false,<br>    };<br>    connect(this, this.#state);<br>  }<br>  get paused() {<br>    return this.#state.isPaused;<br>  }<br>}</pre><p>… which is going to be used by its PauseController ...</p><pre>class PauseController {<br>  #signal;<br>  #signalState;<br><br>  constructor() {<br>    new PausedStateSignal((signal, signalState) =&gt; {<br><br>      this.#signal = signal;<br>      this.#signalState = signalState;<br>    });<br>    this.#signalState.isPaused = false;<br>  }<br>  get signal() {<br>    return this.#signal;<br>  }<br><br>  break() {<br>    const isPaused = this.#signalState.isPaused;<br><br>    if (!isPaused) {<br>      this.#signalState.isPaused = true;<br>    }<br>    this.#signal.dispatchEvent(<br>      new CustomEvent(&#39;break&#39;, { detail: { pausedBefore: isPaused } })<br>    );<br>    return !isPaused;<br>  }<br>  continue() {<br>    const isPaused = this.#signalState.isPaused;<br><br>    if (isPaused) {<br>      this.#signalState.isPaused = false;<br>    }<br>    this.#signal.dispatchEvent(<br>      new CustomEvent(&#39;continue&#39;, { detail: { pausedBefore: isPaused } })<br>    );<br>    return isPaused;<br>  }<br>}</pre><p>… where PausedStateSignal has to extend <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget">EventTarget</a> in order to be able of signaling state-changes via <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent">dispatchEvent</a>, and where PauseController features the two main methods break and continue.</p><p>Both implementations are relying on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">class</a> syntax, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties">private properties</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#using_getters_in_classes">get syntax</a> and a private, protected state object which gets shared by reference in between a controller and a signal instance. The latter gets achieved by a connecting callback function which is passed at a signal&#39;s instantiation time.</p><p>Having covered that part, one can continue with the actual implementation of an array method which, in addition of the standard forEach functionality, is capable of three things ...</p><ul><li>allowing to <strong>pause/halt the callback function’s execution</strong> via break,</li><li>and via continue allowing ...<br> - either to <strong>continue a paused/halted loop</strong>,<br> - or to <strong>skip the loop’s next iteration step</strong>.</li></ul><p>The implementation could be named e.g. forEachAsyncBreakAndContinue; it does make use of the above described signal and controller abstractions, might look like follows ...</p><pre>function forEachAsyncBreakAndContinue(callback, context = null) {<br>  const { promise, reject, resolve } = Promise.withResolvers();<br><br>  const controller = new PauseController;<br>  const { signal } = controller;<br><br>  const arr = this;<br>  const { length } = arr;<br><br>  let idx = -1;<br><br>  function continueLooping() {<br>    while(++idx &lt; length) {<br><br>      if (signal.paused) {<br>        --idx;<br><br>        break;<br>      }<br>      try {<br>        callback.call(context, arr.at(idx), idx, arr, controller);<br><br>      } catch (exception) {<br><br>        reject(exception.message ?? String(exception));<br>      }<br>    }<br>    if (idx &gt;= length) {<br><br>      resolve({ success: true });<br>    }<br>  }<br>  signal.addEventListener(&#39;continue&#39;, ({ detail: { pausedBefore } }) =&gt; {<br>    if (pausedBefore) {<br>      // - continue after already having<br>      //   encountered a break-command before.<br>      continueLooping();<br>    } else {<br>      // - continue-command while already running which<br>      //   is equal to skipping  the next occurring cycle.<br>      ++idx;<br>    }<br>  });<br>  continueLooping();<br><br>  return promise;<br>}</pre><p>… and finally gets assigned for demonstration purposes via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty">Reflect.defineProperty</a> as e.g.forEachAsyncBC to Array.prototype ...</p><pre>Reflect.defineProperty(Array.prototype, &#39;forEachAsyncBC&#39;, {<br>  value: forEachAsyncBreakAndContinue,<br>});</pre><p>The now prototypal forEachAsyncBC method is always going to return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>. This <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">Promise</a> instance either <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject">reject</a>s or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve">resolve</a>s; the former in case the provided callback function does raise an error at any time it gets invoked, and the latter in case the iteration cycle has been fully completed.</p><p>Thanks to all the abstractions <a href="https://codepen.io/petsel/pen/poYMaNz?editors=1012">an executable example code which does test all of the mentioned features</a> can be written as easy as that …</p><pre>(async () =&gt; {<br><br>  const result =  await [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]<br>    .forEachAsyncBC((value, idx, arr, controller) =&gt; {<br><br>      console.log({ value, idx });<br><br>      if (value === 9 || value === 3) {<br>        console.log(`... skip over next value =&gt; ${ arr[idx + 1] } ...`);<br><br>        // skip over.<br>        controller.continue();<br><br>      } else  if (value === 4 || value === 6) {<br><br>        console.log(`... break at value ${ value } ... continue after 5 seconds ...`);<br>        setTimeout(controller.continue.bind(controller), 5000);<br><br>        // break loop.<br>        controller.break();<br>      }<br>    });<br><br>  console.log({ result });<br><br>})();</pre><h4>CODEPEN — executable example code</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fpetsel%2Fembed%2Fpreview%2FpoYMaNz%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DpoYMaNz&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fpetsel%2Fpen%2FpoYMaNz&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FpoYMaNz-512.jpg%3Fversion%3D1708953897&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3472d0e75641127c0426b10a41ccf05/href">https://medium.com/media/e3472d0e75641127c0426b10a41ccf05/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b445d1bc83" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>