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?
>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.