0

I'm writing javascript code to parse a huge file (several GBs) and I'm using FileReader's readAsArrayBuffer function with promises (see below):

        function readRaw(fc, length) {
            const fileReader = new FileReader();

            return new Promise((resolve, reject) => {
                fileReader.onloadend = function(value) {
                    console.log("onloadend");
                    fc.offset += length;
                    resolve(new Uint8Array(value.result));
                }
                fileReader.onerror = (err) => {
                    console.error(err);
                    reject(err);
                }

                const slice = fc.handle.slice(fc.offset, fc.offset + length);
                fileReader.readAsArrayBuffer(slice);
            });
        }

        function parsefile(file) {
            let fc = { handle: file, offset: 0 };
            let buffer = {};

            var promise = readRaw(fc, 32);

            promise.then(function(value) {
                console.log("success: offset=" + fc.offset)
                buffer = value
            }).catch((e) => {
                console.error(e);
            });

            console.log("offset=" + fc.offset);
        }

        document
            .getElementById('fileToRead')
            .addEventListener('change', function () {
                let file = this.files[0];

                if (file) {
                    parsefile(file);
                }
            }, false);

My expectation is that Promise.prototype.then() should wait for the promise to resolve before continuing but I'm not able to get it to work no matter how I tweak the code or switch to use async/await.

Expected:

onloadend
success: offset=32
offset=32

Actual

offset=0
onloadend
success: offset=32

Thanks in advance for any help and enlightenment!

so34x
  • 3
  • 2

1 Answers1

0

Per Why await beats Promise.then(...)"

The fundamental difference between await and vanilla promises is that await X() suspends execution of the current function, while promise.then(X) continues execution of the current function after adding the X call to the callback chain.

jarmod
  • 71,565
  • 16
  • 115
  • 122