You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用async/await读取PDF页数并解决Promise执行器async的ESLint报错?

错误原因

no-async-promise-executor 规则禁止为 new Promise() 的执行器函数添加 async 修饰符。原因是 async 函数本身会返回隐式 Promise,一旦执行器内部抛出异常,异常会被这个隐式 Promise 捕获,无法传递到你外层手动创建的 Promise 中,进而引发未处理的 Promise rejection 问题。

修复思路

你不需要把 axios await 逻辑写在 Promise 执行器内部,当前 findNumberOfPages 本身已经是 async 函数,完全可以先在外部 await 拿到 PDF 响应,再单独用 Promise 封装 FileReader 的回调逻辑,就能同时满足 await axios、回调中 resolve 的需求,同时规避 ESLint 报错。

优化后完整代码

import axios from 'axios'

export const findNumberOfPages = async pdfUrl => {
  try {
    // 直接在async函数作用域内await axios请求
    const response = await axios.get(pdfUrl, {
      headers: { 'Content-Type': 'application/pdf' },
      responseType: 'blob' // 直接返回blob类型,无需手动构造
    })

    // 单独用Promise封装FileReader的异步回调逻辑
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsBinaryString(response.data)
      reader.onloadend = () => {
        const pages = reader.result.match(/\/Type[\s]*\/Page[^s]/g)
        const count = pages?.length
        resolve(count)
      }
      // 补充FileReader的错误处理,避免异常未捕获
      reader.onerror = () => reject(new Error('Failed to read PDF file'))
    })
  } catch (error) {
    throw new Error(`Error when fetching pdf: ${error.message}`)
  }
}

额外说明

原正则匹配 PDF 页数的方案对部分压缩、加密的 PDF 可能不生效,属于业务逻辑范畴可根据需求自行调整。

内容的提问来源于stack exchange,提问作者Henok Tesfaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:24:04