Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Promise with async/await

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

  1. Do I really need async keyword before this function? I think, it does nothing...
  2. Should I create new FileReader in Promise executor function scope or at readAsArrayBuffer scope level? (...or it doesn't matter?)
  3. What I wrote is two functions nested in function nested in function. Am I doing something wrong? :-)
like image 911
Matěj Pokorný Avatar asked Mar 08 '23 10:03

Matěj Pokorný


1 Answers

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. :-)

like image 164
Mattias Buelens Avatar answered Mar 20 '23 08:03

Mattias Buelens