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
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
The FileReader methods work asynchronously but don't return a Promise. And attempting to retrieve the result immediately after calling a method will not work, as the . onload event handler fires only after the FileReader has successfully finished reading the file and updates the FileReader's .
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With