Skip to content

asyncTemplate()

Tagged template that builds an async iterable of string chunks (like a streaming template engine).

Static template parts are yielded as-is. Each interpolated “piece” can be a primitive, a nested array of pieces, a Promise of a piece (including a resolved primitive), an async iterable of primitives, or a zero-arg function whose result is processed the same way (see AsyncTemplatePiece / MaybeFn).

Interpolation handling matches processTemplatePiece: null, undefined, and false add nothing; any other value becomes text via String(...); functions are called once with no arguments before further processing. Collect chunks with for await...of or utilities like Array.fromAsync where available.

Examples:

Plain values and promises:

ts
const gen = asyncTemplate`Hello, ${'world'}! Status: ${Promise.resolve(200)}`;
let out = '';
for await (const chunk of gen) out += chunk;
// out === 'Hello, world! Status: 200'

Falsy pieces are omitted (null, undefined, false); arrays flatten recursively:

ts
const gen = asyncTemplate`${null}${false}A${['B', ['C']]}`;
const out = await Array.fromAsync(gen).then((parts) => parts.join(''));
// out === 'ABC'

Stream from an async iterable (e.g. chunked upstream text):

ts
async function* lines() {
  yield 'line1\n';
  yield 'line2\n';
}
const gen = asyncTemplate`Header\n${lines()}Footer`;

Lazy piece via a thunk (invoked as piece()):

ts
let n = 0;
const gen = asyncTemplate`count=${() => ++n}`;
// first consumption yields "count=1", etc.

Released under the MIT License.