How can I convert an onload promise into Async/Awa

2019-04-07 10:54发布

问题:

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

回答1:

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