typescript - 如何将 onload promise 转换为 Async/Await

标签 typescript promise async-await es6-promise

我有以下 Typescript,我想在上面使用 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 promise 转换为使用 async/await

最佳答案

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

示例消费:

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

关于typescript - 如何将 onload promise 转换为 Async/Await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252194/

相关文章:

typescript - Angular 2 - 销毁子组件

javascript - SequelizeJS 用 promise 返回 "fulfillmentValue"

javascript - 在 Promise 执行器中访问 JS Promise .then()

javascript - 通过github API异步递归获取文件

wpf - caliburn.micro 会在 ViewModel 上使用异步方法做正确的事情吗?

c# - 如何在没有异步 CTP 的情况下实现等待

angular - 如何在angular2 RC5中获取路由参数

typescript - Visual Studio Code 忽略 typescript 版本设置

c# - 在 C# 中的单个调用中进行多个异步调用

TypeScript:如何不使用相对路径导入类?