如何将onload promise转换为Async / Await

时间:2016-07-07 17:55:22

标签: typescript promise async-await es6-promise

我想要使用以下打字稿async / await。但我似乎无法在脑海中解决这个问题。

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

有人可以告诉我如何将此Typescript承诺转换为使用async / await

1 个答案:

答案 0 :(得分:19)

  

TypeScript现在支持对ES6生成器具有本机支持的引擎的异步函数,例如:节点v4及更高版本。异步函数以async关键字为前缀; await挂起执行,直到满足异步函数返回promise,并从返回的Promise中解除值。 - 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);
    });
}

消费示例:

async function caller() {
    var workbook = await this.getWorkbookFromFile2(this.getFile());
    // The 'workbook' variable is an IWorkBook...
}