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

Promise中.catch()无法返回错误名?图片加载函数返回undefined问题

问题根源:异步操作的返回值未正确处理

你的核心问题在于没有让getPic函数正确返回异步操作的结果——Firebase的listAll()和getDownloadURL()都是异步Promise操作,但你之前的代码要么在异步完成前就同步返回了未初始化的图片元素,要么根本没返回异步流程的结果,导致外部调用永远拿不到错误信息,甚至得到undefined。

原代码问题拆解

  1. 第一个版本的问题:

    • 触发Firebase异步请求后,你立刻同步返回了pic,此时异步请求还在进行,pic的src还没设置;
    • catch回调里的return error.name只是回调函数的返回值,不是getPic函数的返回值,外部完全拿不到这个错误。
  2. 第二个版本的问题:

    • 当需要从Firebase加载时,函数没有返回任何值(异步回调里的return不影响外层函数),所以默认返回undefined。

正确实现:让函数返回Promise

我们需要让getPic整体返回一个Promise,这样外部可以等待异步操作完成,同时正确捕获错误。推荐用async/await写法,可读性更强:

async function getPic(index) {
  // 优先读取本地缓存
  if (tempPhotos[index]) {
    console.log("Got it locally");
    return tempPhotos[index];
  }

  try {
    // 从Firebase获取图片列表
    const res = await storageRefPhotos.listAll();
    
    // 先检查索引是否有效,提前抛出错误
    if (!res.items[index]) {
      throw new TypeError("Invalid index: no photo found");
    }

    // 获取图片下载链接
    const url = await res.items[index].getDownloadURL();
    
    // 创建并配置图片元素
    const pic = document.createElement("img");
    pic.src = url;
    pic.classList.add("horizontal");
    
    // 存入缓存
    tempPhotos[index] = pic;
    console.log("Got it from Firebase");
    
    return pic;
  } catch (error) {
    console.log("The function found an " + error.name);
    // 抛出错误,让外部调用者可以捕获
    throw error;
  }
}

修改外部调用逻辑

因为getPic现在返回Promise,你需要用async/await或者.then/.catch来处理结果:

方式1:用async/await(推荐,更直观)

// 把事件监听回调改成async函数
async function handleNextPhoto() {
  try {
    const nextPic = await getPic(currentPhoto + 1);
    // 没有错误则替换图片
    console.log("Executing the else");
    gallery.replaceChild(nextPic, arrow_left.nextElementSibling);
    currentPhoto++;
  } catch (error) {
    // 捕获错误并处理
    if (error.name === "TypeError") {
      console.log("Executing the if");
      console.log("The EventListener found a " + error.name);
    }
  }
}

// 绑定到点击事件
arrow_right.addEventListener("click", handleNextPhoto);

方式2:用.then/.catch

getPic(currentPhoto + 1)
  .then(nextPic => {
    console.log("Executing the else");
    gallery.replaceChild(nextPic, arrow_left.nextElementSibling);
    currentPhoto++;
  })
  .catch(error => {
    if (error.name === "TypeError") {
      console.log("Executing the if");
      console.log("The EventListener found a " + error.name);
    }
  });

关键说明

  • 函数始终返回Promise,不管是缓存命中(同步返回resolved的Promise)还是异步加载,保证了调用接口的一致性;
  • 错误通过throw被包装成rejected的Promise,外部可以通过try/catch或.catch捕获;
  • 提前检查索引有效性,避免Firebase返回的错误不明确,让错误处理更可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:32:49