I'm starting with async/await things in TypeScript and I have few questions about it. I wrote this function to get ArrayBuffer from Blob.
async function readAsArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
return new Promise<ArrayBuffer>((resolve, reject) => {
let reader = new FileReader();
reader.addEventListener('load', e => resolve((<FileReader>e.target).result));
reader.addEventListener('error', e => reject((<FileReader>e.target).error));
reader.readAsArrayBuffer(blob);
});
}
So...
async
keyword before this function? I think, it does nothing...Do I really need async keyword before this function? I think, it does nothing...
Nope. You only really need the async
keyword if you use await
inside your function body.
Should I create new FileReader in Promise executor function scope or at readAsArrayBuffer scope level? (...or it doesn't matter?)
I would recommend keeping most of the actual code inside the executor function. The advantage is that if you have a synchronous exception (e.g. if new FileReader()
were to throw
on construction), the executor will catch that and turn it into an asynchronous promise rejection. If you put it outside the executor function, then your function would throw a synchronous exception. This would be confusing to use, since you'd have to handle both synchronous and asynchronous exceptions separately.
What I wrote is two functions nested in function nested in function. Am I doing something wrong? :-)
It's fine. This is quite a common pattern when you're writing a promise wrapper around a non-promise API. The advantage is that you can now use this wrapper with await
and avoid nested functions in other parts of your code. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With