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

Node.js Twitch bot调用fetch返回undefined问题排查求助

问题根源

返回undefined由三个错误共同导致:

  • fetch是异步API,你当前的isUser函数没有把异步操作的结果返回出去,函数执行到末尾没有显式return,默认就返回undefined
  • 嵌套的then里的return只会把值传给同链上的下一个then,不会直接返回给外层的isUser函数
  • 你原有代码里的用户存在判断逻辑写错了,接口返回的res.data是数组,不能和字符串"undefined"做对比,匹配不到用户时返回的是空数组,不是字符串比对永远为真,会触发后续数组下标读取报错

修复方案

方案1:Promise链式写法

首先修改isUser函数,把所有异步操作的Promise链返回:

// 修改后的isUser函数
function isUser(userLookUp, channel) {
  // 这里加return,把整个fetch的Promise返回出去
  return fetch(
    `https://api.twitch.tv/helix/users?login=${userLookUp.toLowerCase().trim()}`,
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${O_Token}`,
        "Client-Id": C_ID
      }
    }
  )
    .then(res => res.json())
    .then(res => {
      // 修改判断逻辑,判断数组是否有值
      if (res.data && res.data.length) {
        // 这里也要加return,把内层fetch的Promise返回给外层then
        return fetch(
          `https://api.twitch.tv/helix/channels?broadcaster_id=${res.data[0].id}`,
          {
            method: "GET",
            headers: {
              Authorization: `Bearer ${O_Token}`,
              "Client-Id": C_ID
            }
          }
        )
          .then(result => result.json())
          .then(result => {
            return res.data[0].game_name
          });
      } else {
        // 没有查到用户的情况返回空值
        return null
      }
    });
}

调用时需要通过then接收异步返回的结果,不能直接同步打印:

if (doubleCommand[0] === "!shoutout" || doubleCommand[0] === "!so") {
  isUser(doubleCommand[1], channel).then(gameName => {
    console.log(gameName)
  })
}

方案2:async/await写法(更易读,推荐使用)

把isUser改成async函数,用await处理异步逻辑,避免嵌套回调:

async function isUser(userLookUp, channel) {
  try {
    const userRes = await fetch(
      `https://api.twitch.tv/helix/users?login=${userLookUp.toLowerCase().trim()}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${O_Token}`,
          "Client-Id": C_ID
        }
      }
    )
    const userData = await userRes.json()
    if (!userData.data || !userData.data.length) {
      return null
    }
    await fetch(
      `https://api.twitch.tv/helix/channels?broadcaster_id=${userData.data[0].id}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${O_Token}`,
          "Client-Id": C_ID
        }
      }
    )
    return userData.data[0].game_name
  } catch (err) {
    // 可自定义错误处理逻辑
    console.error('查询失败', err)
    return null
  }
}

调用方式和Promise链式写法一致,也可以在async函数内用await直接接收结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:45:00