首页 > 解决方案 > Angular 9 async-await Uncaught (in promise) 错误

问题描述

//to check the uploaded pdf file total pages > 5
static validatePdfFile(event: any) {
    const file = event.target.files[0];
    file.arrayBuffer().then(async buff => {
        let fileUint8Array = new Uint8Array(buff);
        const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false});
        const totalPages = pdfDoc.getPageCount();
        
        if(totalPages > 5) {
            throw new Error('File must be less than 5 pages.');
        }
    });
}

使用异步等待,得到以下异常:

Uncaught (in promise): Error: File must be less than 5 pages.. Error: File must be less than 5 pages. at Function. 
(http://localhost:4200/main.ca25b55f0dfc50ab2.....

从异步抛出新错误的正确方法是什么?

标签: async-awaitangular-promiseangular9

解决方案


:)

validatePdfFile(event: any) {
      const file = event.target.files[0];
      this.PdfPagesCount(file).subscribe(
                (pageCount: number) => {
                    if (pageCount > 5) {
                        throw new Error('File must be less than 5 pages.');
                    } else {
                       //... 
                    }
                },
                (error: any) => {
                    event.target.value = '';
                    throw error;
                }
      );
}

countPdfPages(file: File) {
        return from(file.arrayBuffer().then(
            async buff => {
                const fileUint8Array = new Uint8Array(buff);
                const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false, ignoreEncryption: true});
                return pdfDoc.getPageCount();
            }
        ));
}

推荐阅读