From 9a7e1baa8c579d883a8845d0aa8ce9c6c13305cc Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Tue, 14 Jan 2025 16:01:45 +0100 Subject: [PATCH] fetch: make readAllBytes "sync" --- lib/web/fetch/index.js | 2 +- lib/web/fetch/util.js | 38 +++++++++++++++++++++----------------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/lib/web/fetch/index.js b/lib/web/fetch/index.js index 38bcfd3dfc2..818e8e33e23 100644 --- a/lib/web/fetch/index.js +++ b/lib/web/fetch/index.js @@ -752,7 +752,7 @@ async function mainFetch (fetchParams, recursive = false) { } // 4. Fully read response’s body given processBody and processBodyError. - await fullyReadBody(response.body, processBody, processBodyError) + fullyReadBody(response.body, processBody, processBodyError) } else { // 21. Otherwise, run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) diff --git a/lib/web/fetch/util.js b/lib/web/fetch/util.js index be6060058a3..e3759b2612b 100644 --- a/lib/web/fetch/util.js +++ b/lib/web/fetch/util.js @@ -1240,42 +1240,46 @@ function isomorphicEncode (input) { /** * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes - * @see https://streams.spec.whatwg.org/#read-loop * @param {ReadableStreamDefaultReader} reader * @param {(bytes: Uint8Array) => void} successSteps * @param {(error: Error) => void} failureSteps */ -async function readAllBytes (reader, successSteps, failureSteps) { +function readAllBytes (reader, successSteps, failureSteps) { const bytes = [] - let byteLength = 0 - - try { - do { - const { done, value: chunk } = await reader.read() + readLoop(reader, bytes, successSteps, failureSteps) +} +/** +* @see https://streams.spec.whatwg.org/#read-loop +* @param {ReadableStreamDefaultReader} reader +* @param {Uint8Array[]} bytes +* @param {(bytes: Uint8Array) => void} successSteps +* @param {(error: Error) => void} failureSteps +*/ +function readLoop (reader, bytes, successSteps, failureSteps) { + reader + .read() + .then(({ done, value: chunk }) => { if (done) { - // 1. Call successSteps with bytes. - successSteps(Buffer.concat(bytes, byteLength)) + // 1. Call successSteps with bytes. + successSteps(Buffer.concat(bytes)) return } // 1. If chunk is not a Uint8Array object, call failureSteps // with a TypeError and abort these steps. if (!isUint8Array(chunk)) { - failureSteps(TypeError('Received non-Uint8Array chunk')) + failureSteps(new TypeError('Received non-Uint8Array chunk')) return } // 2. Append the bytes represented by chunk to bytes. bytes.push(chunk) - byteLength += chunk.length - // 3. Read-loop given reader, bytes, successSteps, and failureSteps. - } while (true) - } catch (e) { - // 1. Call failureSteps with e. - failureSteps(e) - } + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + readLoop(reader, bytes, successSteps, failureSteps) + }) + .catch(failureSteps) } /**