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

JS中等待服务端返回数组后push报undefined错误该如何解决?

问题修复方案

错误根源

  • 异步调用时序错误:getData是异步函数,你在handleInputs中调用getData()后立刻执行submitData(),此时网络请求尚未完成,全局变量dataBase还停留在初始的undefined状态,调用push方法自然抛出类型错误。
  • 代码拼写错误:getData函数内的awair res.json()是拼写错误,正确关键字为await。

修复步骤

  1. 将handleInputs改为异步函数,调用getData时添加await关键字,确保接口数据返回、dataBase赋值完成后再执行后续的提交、渲染逻辑
  2. 修正getData内的拼写错误
  3. 可添加兜底判断,避免接口返回非数组值时再次报错

修复后代码示例

var dataBase;

const getData = async() => {
    const url = 'http://localhost:8080/readData';
    const res = await fetch(url);
    const data =  await res.json(); // 修正拼写错误
    // 兜底逻辑:如果接口返回非数组,默认赋值为空数组,避免后续报错
    dataBase = Array.isArray(data) ? data : [];
}

// handleInputs改为异步函数
const handleInputs = async () => {
    if (userName.value === "" && password.value === "" && repeatPassword.value === "" && checkTerms.checked) {
        alert('Please fill the input');
    } else {
        if (password.value === repeatPassword.value) {
            await getData(); // 增加await,等待数据获取完成后再执行后续逻辑
            submitData();
            renderUser();
            form.reset();
        } else {
            alert('Password does not match with repeat password input')
        }

    }
}

const submitData = () => {
    let userObj = {
        userName: userName.value,
        password: password.value,
        id: countId++
    }

    dataBase.push(userObj);
    sendData();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:45:05