From 59fbad617b35d3a4a90b8e4ea3016b94ed4d423f Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Sat, 14 Feb 2026 15:19:58 +0100 Subject: [PATCH] Convert `ChunkedStreamManager.prototype.sendRequest` to an asynchronous method This is not only shorter, but (in my opinion) it also simplifies the code. *Note:* In order to keep the *five* different `BasePDFStreamRangeReader` implementations consistent, we purposely don't re-factor the `PDFWorkerStreamRangeReader` class to support `for await...of` iteration. --- src/core/chunked_stream.js | 59 ++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 34 deletions(-) diff --git a/src/core/chunked_stream.js b/src/core/chunked_stream.js index 3b712c15a..367ac75c1 100644 --- a/src/core/chunked_stream.js +++ b/src/core/chunked_stream.js @@ -293,46 +293,37 @@ class ChunkedStreamManager { this.msgHandler = args.msgHandler; } - sendRequest(begin, end) { + async sendRequest(begin, end) { const rangeReader = this.pdfStream.getRangeReader(begin, end); - let chunks = []; - return new Promise((resolve, reject) => { - const readChunk = ({ value, done }) => { - try { - if (done) { - resolve( - chunks.length > 0 || !this.disableAutoFetch - ? arrayBuffersToBytes(chunks) - : null - ); - chunks = null; - return; - } - if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) { - assert( - value instanceof ArrayBuffer, - "readChunk (sendRequest) - expected an ArrayBuffer." - ); - } - chunks.push(value); - rangeReader.read().then(readChunk, reject); - } catch (e) { - reject(e); - } - }; - rangeReader.read().then(readChunk, reject); - }).then(data => { + + while (true) { + const { value, done } = await rangeReader.read(); + if (this.aborted) { + chunks = null; return; // Ignoring any data after abort. } - if (!data) { - // The range request wasn't dispatched, see the "GetRangeReader" handler - // in the `src/display/api.js` file. - return; + if (done) { + break; } - this.onReceiveData({ chunk: data.buffer, begin }); - }); + if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) { + assert( + value instanceof ArrayBuffer, + "sendRequest - expected an ArrayBuffer." + ); + } + chunks.push(value); + } + + if (chunks.length === 0 && this.disableAutoFetch) { + // The range request wasn't dispatched, see the "GetRangeReader" handler + // in the `src/display/api.js` file. + return; + } + const data = arrayBuffersToBytes(chunks); + chunks = null; + this.onReceiveData({ chunk: data.buffer, begin }); } /**