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

使用fetch请求名言API获取随机名言返回undefined如何解决

问题根源

你代码出现undefined的核心原因有两个:

  1. fetch是异步API,getQuote()返回的是Promise实例,不是接口返回的名言数据对象,直接访问Promise的text/author属性必然是undefined
  2. 连续两次调用getQuote()会发起两次独立的接口请求,最终拿到的是两条不同的随机名言,不符合使用预期

修复方案

第一步:完善getQuote函数的异常处理,从根源避免返回undefined

给请求失败、响应为空的场景增加默认返回值,还可以增加缓存减少重复请求:

function getQuote() {
  // 增加缓存,避免每次获取都发起请求
  if (window.quoteCache) {
    return Promise.resolve(window.quoteCache[Math.floor(Math.random() * window.quoteCache.length)])
  }

  return fetch('https://type.fit/api/quotes')
    .then(response => {
      // 判断响应是否正常,避免接口报错时解析失败
      if (!response.ok) throw new Error('接口请求异常')
      return response.json()
    })
    .then(jsonResponse => {
      if (!Array.isArray(jsonResponse) || !jsonResponse.length) {
        return { text: '人生在勤,不索何获', author: '张衡' }
      }
      // 缓存请求结果
      window.quoteCache = jsonResponse
      return jsonResponse[Math.floor(Math.random() * jsonResponse.length)]
    })
    .catch(err => {
      console.error('名言获取失败:', err)
      // 异常场景返回默认值,彻底避免undefined
      return { text: '人生在勤,不索何获', author: '张衡' }
    })
}

第二步:正确处理异步返回结果

你可以选择两种写法处理异步结果:

  1. then链式调用写法
getQuote().then(quote => {
  const textQuote = quote.text
  const authorQuote = quote.author
  // 后续业务逻辑写在这里,比如渲染到页面
  console.log(textQuote, authorQuote)
})
  1. async/await写法(更易读)
async function loadQuote() {
  const quote = await getQuote()
  const textQuote = quote.text
  const authorQuote = quote.author
  // 后续业务逻辑写在这里
  console.log(textQuote, authorQuote)
}
// 执行函数
loadQuote()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 16:39:01