Async Patterns

← Programming Idioms
STRVCT

Promise extensions, serial and parallel async array iteration, and error context rethrowing with Error.rethrow().

Overview

STRVCT extends native JavaScript Promise and Array prototypes via categories (Promise_ideal.js, Array_promises.js) to provide clean, chainable asynchronous primitives without importing external async utility libraries.

Array_promises Extensions promiseSerialForEach / Map Promise_ideal Extensions status, timeouts, & clone() Error.rethrow() Context Chained error stack traces Asynchronous array operations execute cleanly in serial sequence or bounded parallel batches without raw promise boilerplate.

Async Array Iteration (`Array_promises.js`)

STRVCT adds asynchronous iteration methods directly to Array.prototype:

1. Serial Execution (promiseSerialForEach / promiseSerialMap)

Executes an async callback for each element in strict sequential order, awaiting each element before starting the next:

// Executes sequentially
await items.promiseSerialForEach(async (item) => {
    await processItem(item);
});

// Maps results sequentially
const results = await items.promiseSerialMap(async (item) => {
    return await fetchDetails(item);
});

2. Parallel Execution (promiseParallelMap)

Executes async callbacks in parallel across all array elements:

const results = await items.promiseParallelMap(async (item) => {
    return await fetchDetails(item);
});

Promise Extensions (`Promise_ideal.js`)

Promise_ideal.js extends Promise with status introspection and timeout helpers:

const promise = Promise.clone(); // Instantiates wrapper promise
promise.isPending();             // Returns true while unresolved
promise.isResolved();            // Returns true when resolved
promise.isRejected();            // Returns true on rejection

// Timeout protection
await promise.timeout(5000, "Operation timed out after 5s");

Chained Error Context (`Error.rethrow()`)

When catching and rethrowing errors in async pipelines, Error.rethrow() preserves the original error stack while adding contextual messages:

try {
    await pool.commitStoreDirtyObjects();
} catch (error) {
    throw Error.rethrow(`Failed to commit object pool ${pool.poolId()}`, error);
}