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

Node.js获取MySQL最大ID返回undefined的问题排查

问题分析与解决方案

核心问题拆解

  1. 初始代码中await失效的原因
    你给getNumberOfRow加了async,但函数内部并没有返回axios.get的Promise对象——而是直接执行了return;,所以mintNFT里的await等待的是一个undefined,自然会先打印this is id undefined,等异步请求完成后才会输出response内容。

  2. 编辑后仍返回undefined的原因
    后端返回的response.data[0]是一个对象{MAX(id): 154},而非数组,你用response.data[0][0]去取值必然得到undefined。另外直接用MAX(id)作为属性名不够直观,还容易出问题。


完整修复步骤

1. 后端SQL查询优化(给聚合结果起别名)

修改index.js中的SQL语句,给MAX(id)指定别名,方便前端取值:

app.get("/getNumberOfRow", (req, res) => {
    db.query("SELECT MAX(id) AS max_id FROM NFTDetails", (err, result) => {
        if (err) {
            console.log(err);
            return res.status(500).send({ error: err.message }); // 主动返回错误状态,避免前端挂起
        }
        res.send(result);
    });
})

2. 前端函数修正(正确返回Promise并取值)

修改abc.jsx中的getNumberOfRow函数,确保返回异步请求的结果,并正确提取属性值:

async function getNumberOfRow() {
  try {
    const response = await axios.get("http://localhost:4000/getNumberOfRow");
    // response.data是查询结果数组,第一行就是包含max_id的对象
    const maxId = response.data[0].max_id;
    console.log("获取到的最大ID", maxId);
    return maxId;
  } catch (err) {
    console.error("获取最大ID失败", err);
    return 0; // 或根据业务需求返回默认值
  }
}

3. 验证效果

此时mintNFT中的await getNumberOfRow()会正确等待异步请求完成,拿到真实的最大ID后再执行console.log,输出顺序和值都会符合预期。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:31:57