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

JavaScript脚本执行过快致变量未赋值问题求助

解决异步fetch导致变量未赋值的问题

你遇到的是前端异步编程里非常常见的问题——fetch是异步操作,你的checkUsersExist函数没有返回异步操作的结果,导致createUser里的if判断在请求完成前就执行了,所以check始终是undefined。

问题根源

fetch发起HTTP请求后,不会阻塞后续代码的执行,你的checkUsersExist函数在调用fetch后就直接结束了(默认返回undefined),而此时后端的响应还没回来,自然拿不到正确的check值。

解决方案

我们需要让checkUsersExist返回一个Promise,这样就能在createUser里等待异步请求完成后再执行判断逻辑。

1. 修改checkUsersExist函数,返回Promise并解析响应

function checkUsersExist(userName){ 
  let headers = new Headers(); 
  headers.append('Content-Type', 'application/json'); 
  const init = { 
    method: 'PUT', 
    headers: headers, 
    body: JSON.stringify({ userName }), // 用JSON.stringify替代模板字符串,避免语法问题
    cache: 'no-cache', 
    mode: 'cors' 
  }; 
  const request = new Request('http://localhost:3000/users/check', init); 
  
  // 返回fetch的Promise链,让上层可以等待结果
  return fetch(request) 
    .then(response => { 
      console.log("Response", response, "Request sent to server", request) 
      // 解析后端返回的JSON数据
      return response.json(); 
    }) 
    .catch(err => { 
      console.error(err);
      // 出错时返回标识,便于上层处理
      return "error";
    }); 
}

2. 用async/await改造createUser函数(推荐,代码更直观)

给createUser加上async关键字,用await等待checkUsersExist的异步结果:

async function createUser(){ 
  const userName = document.getElementById("create_username").value;
  const password = document.getElementById("create_password").value; 
  
  console.log("Create user") 
  console.log("Username:", userName, "Password:", password) 
  
  // 等待异步请求完成,拿到真正的check值
  const check = await checkUsersExist(userName) 
  
  console.log("Svar fra checkUsers", check) 
  if(check === "true"){ 
    console.log("UserName already exists") 
  }else if(check === "false") { 
    console.log("UserName is available") 
  }else{ 
    console.log("An error has occurred") 
  } 
}

备选:用.then()链式调用处理结果

如果你不想用async/await,也可以用传统的Promise链式调用:

function createUser(){ 
  const userName = document.getElementById("create_username").value;
  const password = document.getElementById("create_password").value; 
  
  console.log("Create user") 
  console.log("Username:", userName, "Password:", password) 
  
  checkUsersExist(userName)
    .then(check => {
      console.log("Svar fra checkUsers", check) 
      if(check === "true"){ 
        console.log("UserName already exists") 
      }else if(check === "false") { 
        console.log("UserName is available") 
      }else{ 
        console.log("An error has occurred") 
      } 
    })
    .catch(err => {
      console.error("An error has occurred", err);
    });
}

后端小优化(可选)

Express框架里res.json(200, check)是旧写法,建议改成标准的:

res.status(200).json(check);

这样就能保证在拿到后端返回的true/false后,再执行if判断,不会再出现check为undefined的情况了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:33:43