我有以下 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/