Improve bufferFromStream (#5826)

This commit is contained in:
Marcos Casagrande 2020-05-25 15:14:01 +02:00 committed by GitHub
parent fbbb9f1c36
commit c9f0e34e29
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -59,18 +59,16 @@ function concatenate(...arrays: Uint8Array[]): ArrayBuffer {
return result.buffer as ArrayBuffer;
}
function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> {
return new Promise((resolve, reject): void => {
async function bufferFromStream(
stream: ReadableStreamReader
): Promise<ArrayBuffer> {
const parts: Uint8Array[] = [];
const encoder = new TextEncoder();
// recurse
(function pump(): void {
stream
.read()
.then(({ done, value }): void => {
if (done) {
return resolve(concatenate(...parts));
}
while (true) {
const { done, value } = await stream.read();
if (done) break;
if (typeof value === "string") {
parts.push(encoder.encode(value));
@ -79,16 +77,11 @@ function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> {
} else if (!value) {
// noop for undefined
} else {
reject("unhandled type on stream read");
throw new Error("unhandled type on stream read");
}
}
return pump();
})
.catch((err): void => {
reject(err);
});
})();
});
return concatenate(...parts);
}
export const BodyUsedError =