Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an onload promise into Async/Await

I have the following Typescript that I would like to use async/await on. But I can't seem to sort it out in my head how to do this.

private getWorkbookFromFile2(excelFile: File): Promise<xlsx.IWorkBook> {
    var loadedPromise = new Promise<xlsx.IWorkBook>((resolve, reject) => {
        var reader = new FileReader();

        reader.onload = (event: any) => {
            var data = event.target.result;

            var workbook = xlsx.read(data, { type: 'binary' });

            console.log(workbook.SheetNames);
            resolve(workbook);
        };
        reader.readAsBinaryString(excelFile);
    });

    return loadedPromise;
}

Can someone show me how this Typescript promise can be converted to use async/await

like image 704
Vaccano Avatar asked Jul 07 '16 17:07

Vaccano


People also ask

Can I use async await instead of promises?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

Can you use await on a promise?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.

Is FileReader onload async?

The FileReader methods work asynchronously but don't return a Promise. And attempting to retrieve the result immediately after calling a method will not work, as the . onload event handler fires only after the FileReader has successfully finished reading the file and updates the FileReader's .


Video Answer


1 Answers

TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above. Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned. - Source

async function getWorkbookFromFile2(excelFile: File) {
    return new Promise<xlsx.IWorkBook>((resolve, reject) => {
        var reader = new FileReader();

        reader.onload = (event: any) => {
            var data = event.target.result;

            var workbook = xlsx.read(data, { type: 'binary' });

            console.log(workbook.SheetNames);
            resolve(workbook);
        };
        reader.readAsBinaryString(excelFile);
    });
}

Example consumption:

async function caller() {
    var workbook = await this.getWorkbookFromFile2(this.getFile());
    // The 'workbook' variable is an IWorkBook...
}
like image 185
David Pine Avatar answered Sep 20 '22 11:09

David Pine