Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript filereader appears to be defined backwards

So i have some Javascript code that is verified to work. Here is the code with the details removed:

const imgPromise = new Promise((resolve, reject) => 
{
    const reader = new FileReader();
    reader.readAsBinaryString(inputFile[0]);
    reader.onload = function(event)
    {
        resolve();
    }
    reader.onerror = function()
    {
        reject();
    }
});

I understand the code but it appears to me that it is in the wrong order. It would make sense to me if onload an onerror were defined before calling readasbinarystring but it seems to work in the opposite way. can someone explain what exactly is going on here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

readAsBinaryString will fire its load and error events asynchronously, so the code is OK – the current running script will have time to attach the load and error listeners before the engine actually starts reading the blob or file. See the specification The first time the file reader’s error or result could be set to something other than the default value (of null) is after this step runs:

Wait for chunkPromise to be fulfilled or rejected.

Which takes a (tiny) bit of time.

If readAsBinaryString were synchronous, and it read the object immediately, you’d be right, it would only make sense to attach the listeners immediately – but in that case, there wouldn’t be need for asynchronous callbacks at all, and try/catch could make more sense, allowing for synchronous processing.

Also note that nowadays, you should prefer FileReader.readAsArrayBuffer() instead of .readAsBinaryString.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading