diff options
author | Marcos Casagrande <marcoscvp90@gmail.com> | 2020-05-25 15:14:01 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-25 09:14:01 -0400 |
commit | c9f0e34e294241541ba59c3a7eb52f42df7ff993 (patch) | |
tree | 3e76d9c42263078a35d2fe22087571ca46611a38 /cli/js | |
parent | fbbb9f1c36db526edc136fa2ecc4e6aba022099b (diff) |
Improve bufferFromStream (#5826)
Diffstat (limited to 'cli/js')
-rw-r--r-- | cli/js/web/body.ts | 49 |
1 files changed, 21 insertions, 28 deletions
diff --git a/cli/js/web/body.ts b/cli/js/web/body.ts index f65ed9cd0..f0d88be4b 100644 --- a/cli/js/web/body.ts +++ b/cli/js/web/body.ts @@ -59,36 +59,29 @@ function concatenate(...arrays: Uint8Array[]): ArrayBuffer { return result.buffer as ArrayBuffer; } -function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> { - return new Promise((resolve, reject): void => { - const parts: Uint8Array[] = []; - const encoder = new TextEncoder(); - // recurse - (function pump(): void { - stream - .read() - .then(({ done, value }): void => { - if (done) { - return resolve(concatenate(...parts)); - } +async function bufferFromStream( + stream: ReadableStreamReader +): Promise<ArrayBuffer> { + const parts: Uint8Array[] = []; + const encoder = new TextEncoder(); - if (typeof value === "string") { - parts.push(encoder.encode(value)); - } else if (value instanceof ArrayBuffer) { - parts.push(new Uint8Array(value)); - } else if (!value) { - // noop for undefined - } else { - reject("unhandled type on stream read"); - } + while (true) { + const { done, value } = await stream.read(); + + if (done) break; + + if (typeof value === "string") { + parts.push(encoder.encode(value)); + } else if (value instanceof ArrayBuffer) { + parts.push(new Uint8Array(value)); + } else if (!value) { + // noop for undefined + } else { + throw new Error("unhandled type on stream read"); + } + } - return pump(); - }) - .catch((err): void => { - reject(err); - }); - })(); - }); + return concatenate(...parts); } export const BodyUsedError = |