对 void 方法的承诺

时间:2021-07-21 01:40:01

标签: typescript promise void

我实现了一种将文档下载到 Angular 中的 Excel 电子表格的方法,如下所示。有人可以让我知道如何为以下 void 方法实现承诺。

ExportService 类:

export class ExportService {

    constructor() { }

    fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
    fileExtension = '.xlsx';

    public exportExcel(jsonData: any[][], fileName: string): void {
        const x: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData[0]);
        const z: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData[1]);

        const b: XLSX.WorkBook = {
            Sheets: {
                'product': x,
                'sales': z
            },
            SheetNames: ['product', 'sales']
        };
        const excelBuffer: any = XLSX.write(b, { bookType: 'xlsx', type: 'array' });

        this.saveExcelFile(excelBuffer, fileName);
    }

    private saveExcelFile(buffer: any, fileName: string): void {
        const data: Blob = new Blob([buffer], { type: this.fileType });
        FileSaver.saveAs(data, fileName + this.fileExtension);
    }
}

组件中的导出方法如下。

    export() {
        this.callProgress = true;
        this.progressText = "";
    
        this.salesProductForABC().then(() => {
            let products: Array<Array<any>> = [];
            products.push(this.productContent, this.salesProductContent);
    
            let month = new Date().getUTCMonth() + 1;
            let day = new Date().getUTCDate();
            let year = new Date().getUTCFullYear();
            let fileName = `${month}${day}${year}`;
            this.exportService.exportExcel(products, fileName)
            this.callProgress = false;
        })
      }
``

`

1 个答案:

答案 0 :(得分:1)

  1. 从您的服务返回承诺以等待他们

改变

this.saveExcelFile(excelBuffer, fileName);

return this.saveExcelFile(excelBuffer, fileName);

FileSaver.saveAs(data, fileName + this.fileExtension);

return FileSaver.saveAs(data, fileName + this.fileExtension);

当然,您需要将 void 更改为返回类型。

  1. 使函数 exportExcelsaveExcelToFile 异步以便能够等待它们

例如

public exportExcel(jsonData: any[][], fileName: string): void {

public async exportExcel(jsonData: any[][], fileName: string): Promise<void> {
  1. 使用 finally 并添加错误处理

改变

this.exportService.exportExcel(products, fileName)
this.callProgress = false;

this.exportService.exportExcel(products, fileName).catch(e => 
alert(e.message)).finally(() => this.callProgress = false;)
  1. salesProductForABC 添加错误处理并添加正确的 catch

在 Promise 中缺少错误提示是非常糟糕的做法,并且会给用户带来令人沮丧的错误。请记住 - 在您的代码/基础设施/程序输入中,一切都可能被破坏。不要离开很重要:

  • 没有返回承诺
  • 未处理的异常

最后,您的代码不包含 FileSaver,但您可能还应该返回 promise,并且还应该处理接收。

相关问题