Using Promise with async / await

I am a beginner with async / wait for events in TypeScript and I have a few questions about this. 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...

  • Do I really need a keyword async

    before this function? I think it does nothing ...
  • Should I create a new FileReader at the Promise executor function scope or at the scopeAsArrayBuffer level? (... or doesn't it matter?)
  • I wrote two functions nested within a function nested within a function. Am I doing something wrong? :-)
+3


source to share


2 answers


Do I really need the async keyword before this function? I think it does nothing ...

Nope. You only really need the keyword async

if you are using await

inside the body of your function.

Should I create a new FileReader object in the scope of the executors of the Promise or in the scope of the AsAsrayBuffer? (... or doesn't it matter?)



I would recommend keeping most of the actual code inside the executor function. The advantage is that if you have a synchronous exception (for example, if new FileReader()

there was throw

during construction), the executor will catch this and turn it into an asynchronous promise. If you put it outside of the executor function, then your function will throw a synchronous exception. This is confusing to use as you will have to handle both synchronous and asynchronous exceptions separately.

What I wrote is two functions nested within a function nested within a function. Am I doing something wrong? :-)

It's good. This is a fairly common example where you are writing a promise wrapper around a promiseless API. The advantage is that you can now use this wrapper with await

and avoid nested functions in other parts of your code. :-)

+3


source


  • Do I need the async keyword before this function? I think it does nothing ...

No, you only need it async

when the function uses a keyword await

that makes the function execute asynchronously, which is not the case in your function: it runs synchronously with completion. The asynchronous part is only in triggering callbacks, which is not a keyword async

.

  1. Should I create a new FileReader at the Promise executor function scope or at the scopeAsArrayBuffer level? (... or doesn't it matter?)


The best practice is to define variables in the smallest scope needed to work. Although this will work anyway, since you now have it better.

  1. I wrote two functions nested within a function nested within a function. Am I doing something wrong? :-)

There is nothing wrong.

+3


source







All Articles