run-async.js
This file
Path
lib/transform/run-async.js
60 lines · 1.7 KiB · JavaScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 1–60why, one step back1import {callbackify} from 'node:util';23// Applies a series of generator functions asynchronously4export const pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {5 state.currentIterable = getChunks(...getChunksArguments);67 try {8 for await (const chunk of state.currentIterable) {9 transformStream.push(chunk);10 }11 } finally {12 delete state.currentIterable;13 }14});1516// For each new chunk, apply each `transform()` method17export const transformChunk = async function * (chunk, generators, index) {18 if (index === generators.length) {19 yield chunk;20 return;21 }2223 const {transform = identityGenerator} = generators[index];24 for await (const transformedChunk of transform(chunk)) {25 yield * transformChunk(transformedChunk, generators, index + 1);26 }27};2829// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms30export const finalChunks = async function * (generators) {31 for (const [index, {final}] of Object.entries(generators)) {32 yield * generatorFinalChunks(final, Number(index), generators);33 }34};3536const generatorFinalChunks = async function * (final, index, generators) {37 if (final === undefined) {38 return;39 }4041 for await (const finalChunk of final()) {42 yield * transformChunk(finalChunk, generators, index + 1);43 }44};4546// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors47export const destroyTransform = callbackify(async ({currentIterable}, error) => {48 if (currentIterable !== undefined) {49 await (error ? currentIterable.throw(error) : currentIterable.return());50 return;51 }5253 if (error) {54 throw error;55 }56});5758const identityGenerator = function * (chunk) {59 yield chunk;60};