typescript 如何将 onload 承诺转换为 Async/Await

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38252194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:38:02  来源:igfitidea点击:

How can I convert an onload promise into Async/Await

typescriptpromiseasync-awaites6-promise

提问by Vaccano

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

我有以下我想在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;
}

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

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

回答by David Pine

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

TypeScript 现在支持对 ES6 生成器具有本机支持的引擎的异步函数,例如 Node v4 及更高版本。异步函数以 async 关键字为前缀;await 挂起执行,直到异步函数返回承诺完成并从返回的承诺中解包值。-来源

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