Skip to content

Commit 59fbad6

Browse files
committed
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.
1 parent b6d0284 commit 59fbad6

1 file changed

Lines changed: 25 additions & 34 deletions

File tree

src/core/chunked_stream.js

Lines changed: 25 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -293,46 +293,37 @@ class ChunkedStreamManager {
293293
this.msgHandler = args.msgHandler;
294294
}
295295

296-
sendRequest(begin, end) {
296+
async sendRequest(begin, end) {
297297
const rangeReader = this.pdfStream.getRangeReader(begin, end);
298-
299298
let chunks = [];
300-
return new Promise((resolve, reject) => {
301-
const readChunk = ({ value, done }) => {
302-
try {
303-
if (done) {
304-
resolve(
305-
chunks.length > 0 || !this.disableAutoFetch
306-
? arrayBuffersToBytes(chunks)
307-
: null
308-
);
309-
chunks = null;
310-
return;
311-
}
312-
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
313-
assert(
314-
value instanceof ArrayBuffer,
315-
"readChunk (sendRequest) - expected an ArrayBuffer."
316-
);
317-
}
318-
chunks.push(value);
319-
rangeReader.read().then(readChunk, reject);
320-
} catch (e) {
321-
reject(e);
322-
}
323-
};
324-
rangeReader.read().then(readChunk, reject);
325-
}).then(data => {
299+
300+
while (true) {
301+
const { value, done } = await rangeReader.read();
302+
326303
if (this.aborted) {
304+
chunks = null;
327305
return; // Ignoring any data after abort.
328306
}
329-
if (!data) {
330-
// The range request wasn't dispatched, see the "GetRangeReader" handler
331-
// in the `src/display/api.js` file.
332-
return;
307+
if (done) {
308+
break;
333309
}
334-
this.onReceiveData({ chunk: data.buffer, begin });
335-
});
310+
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
311+
assert(
312+
value instanceof ArrayBuffer,
313+
"sendRequest - expected an ArrayBuffer."
314+
);
315+
}
316+
chunks.push(value);
317+
}
318+
319+
if (chunks.length === 0 && this.disableAutoFetch) {
320+
// The range request wasn't dispatched, see the "GetRangeReader" handler
321+
// in the `src/display/api.js` file.
322+
return;
323+
}
324+
const data = arrayBuffersToBytes(chunks);
325+
chunks = null;
326+
this.onReceiveData({ chunk: data.buffer, begin });
336327
}
337328

338329
/**

0 commit comments

Comments
 (0)