【问题标题】:Promise for a void method一个 void 方法的承诺
【发布时间】:2021-09-28 10:46:59
【问题描述】:

我已经实现了一种将文档下载到 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;
        })
      }
``

`

【问题讨论】:

  • 要让一个 void 函数返回一个 promise(换句话说,让 void 异步函数),让它的返回类型为 Promise&lt;void&gt;。你指的是哪些方法? exportExcel 内部没有任何异步代码(即使用 async/await 关键字的代码)。
  • @Hcaertnit Iam 指的是 ExportService 类中的方法。如何在其中实现 then()?
  • @Hcaertnit 我之所以要实现一个promise是,我在上面的export()方法中实现了一个加载器,但是我希望加载器加载到excel表格完成下载。跨度>

标签: typescript promise void


【解决方案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,并且还应该处理接收。

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2014-11-11
    • 2015-06-05
    • 2015-09-26
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多