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

fetch API如何链式调用到多个函数及showQuestion未定义报错修复

报错原因
  • 你在第二层then回调的大括号内用const声明了showQuestion变量,这类块级作用域的变量只能在当前大括号范围内生效,外部定义的questionFetch函数无法访问该变量,调用时就会抛出未定义错误。
  • 代码还存在隐藏问题:randomCatyId.clues[randomData]中的randomData变量没有提前定义,后续执行也会触发同类报错。
修复方案

将showQuestion作为参数传递给questionFetch函数,同时提前定义好randomData变量即可,修复后完整代码如下:

// 示例取分类下索引为0的题目,需要随机取题可自行修改为随机数生成逻辑
const randomData = 0;
// 确保showCategory、h2Question两个DOM元素已提前获取定义
let showCategory = document.querySelector('你对应的分类元素选择器');
let h2Question = document.querySelector('你对应的问题h2元素选择器');

fetch(
    'https://jservice.kenzie.academy/api/random-clue?valid=true'
)
    .then(response => response.json())
    .then(randomDataId => {
        const categoryDataId = randomDataId.categoryId;
        console.log(`category id is: ${categoryDataId}`);

        fetch(
            `https://jservice.kenzie.academy/api/clues?category=${categoryDataId}`
        )
            .then(response => response.json())
            .then(randomCatyId => {
                const rightAnswer = randomCatyId.clues[randomData].answer;
                const showTitle = randomCatyId.clues[randomData].category.title;
                const showQuestion = randomCatyId.clues[randomData].question;

                showCategory.innerText = `Category: ${showTitle}`;
                h2Question.innerText = `Question: ${showQuestion}`;

                console.log('question: ' + showQuestion);
                console.log('answer: ' + rightAnswer);

                // 把showQuestion作为参数传入调用的函数
                questionFetch(showQuestion);
            });
    });

// 函数接收传入的showQuestion参数
function questionFetch(showQuestion) {
    h2Question.innerHTML = `Question: ${showQuestion}`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:27:03