How can I convert an onload promise into Async/Await

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!