Skip to content
Myr

run-async.js

This file

Path

lib/transform/run-async.js

60 lines · 1.7 KiB · JavaScript

Last changed by

Add more code comments (#984)ehmickybefore adoptionfdd8a9f

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–2why, one step back
1import {callbackify} from 'node:util';
2

Add more code comments (#984)ehmickybefore adoptionfdd8a9f

line 3why, one step back
3// Applies a series of generator functions asynchronously

Upgrade xo (#980)ehmickybefore adoptionccfa412

lines 4–5why, one step back
4export const pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {
5 state.currentIterable = getChunks(...getChunksArguments);

Rename files (#977)ehmickybefore adoption4b2e316

lines 6–60why, one step back
6
7 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};