我怎么能转换成一个onload事件的诺言成异步/等待 [英] How can I convert an onload promise into Async/Await
问题描述
我有以下的打字稿,我想用异步
/ 等待
上。但我似乎无法在我的头上理清如何做到这一点。
私人getWorkbookFromFile2(excelFile:文件):无极< xlsx.IWorkBook> {
VAR loadedPromise =新承诺< xlsx.IWorkBook>((解决,拒绝)=> {
VAR读卡器=新的FileReader(); reader.onload =(事件:任意)=> {
VAR数据= event.target.result; VAR工作簿= xlsx.read(数据,{类型:'二进制'}); 的console.log(workbook.SheetNames);
解决(练习册);
};
reader.readAsBinaryString(excelFile);
}); 返回loadedPromise;
}
有人能告诉我这个打字稿承诺如何转化为使用异步
/ 等待
打字稿现在支持异步功能引擎,具有ES6发电机,例如原生支持节点v4和上方。异步功能与async关键字pfixed $ P $;等待暂停执行,直到一个异步函数返回的承诺得到满足,并解开自许返回的值。 - 来源
块引用>异步函数getWorkbookFromFile2(excelFile:文件){
返回新承诺< xlsx.IWorkBook>((解决,拒绝)=> {
VAR读卡器=新的FileReader(); reader.onload =(事件:任意)=> {
VAR数据= event.target.result; VAR工作簿= xlsx.read(数据,{类型:'二进制'}); 的console.log(workbook.SheetNames);
解决(练习册);
};
reader.readAsBinaryString(excelFile);
});
}例如功耗:
异步调用函数(){
变种簿=等待this.getWorkbookFromFile2(this.getFile());
//在工作簿变量是一个IWorkBook ...
}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
解决方案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... }
这篇关于我怎么能转换成一个onload事件的诺言成异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!