The answer from @Arun Killu is a good snippet if you know what is going on, but I think nobody is explaininghas explained what was the error on the original code. For people using async
and Promise
calls this is error is soo obvious but for people learning or without experience it is not so clear.
Here a simple explanation.
Above code is trying to capture a binary string on source
variable, however, FileReader.readAsBinaryString()
returns undefined
. Moreover, the result will be available when the event onload
will be triggered. As youwe can see, he is trying to console logconsole.log
the event.target.result
value, which is a wrong approach.
Well young Padawan, asynchronous means that we don't know when the result will be ready, it can be different in each system and depends on how heavy or complex is the process and also it can havefind some errors that will not produce any result at all.
So if a process is asynchronous is a good practice to encapsulate it using an async
method and returning a Promise
like this:
Ah okay Teo, but what is a Promise?
Good question my young fella. A Promise
object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. In other words, will tell us if the result is ready and will give us its value, otherwise will return an error.
How we can intragratewe integrate it tointo our code?
Super easy, just replace all the FileReader with the function blobToBase64
defined above and call it like this imageBase64 = await blobToBase64(imageBlob)
Check
Check this snippet: