【问题标题】:Missing initializer in const declaration in node js节点js中的const声明中缺少初始化程序
【发布时间】:2021-12-30 10:46:51
【问题描述】:

我正在编写 mysql 查询并将这些记录保存在变量中,我的要求是在任何地方访问该变量,因此在路由之外声明它,但它显示如下错误: SyntaxError: const 声明中缺少初始化程序

const totalQuery = "select name from users";
   
    const totalRecords;
    dbConn.query(totalQuery,function(err,rows)     {
        totalRecords = rows.length
      
    })
    console.log('::'+ totalRecords);
    process.exit();

错误:

SyntaxError: Missing initializer in const declaration

【问题讨论】:

  • 当您创建常量时,您需要使用= 对其进行初始化。您不能声明它,然后在稍后为其分配一个值,因为您需要let(请参阅此MDN article)。请注意,您的代码看起来也将面临以下问题:Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
  • @NickParsons 能否请您在评论中更新。
  • 抱歉,不太清楚您所说的“更新评论”是什么意思?
  • console.log('::'+ totalRecords); 在回调函数中的代码之前运行:totalRecords = rows.length。这就是为什么当你记录它时totalRecordsundefined。将 console.log('::'+ totalRecords); 和任何其他依赖于 rows 的代码移到回调函数中。
  • 另请阅读:How to return the response from an asynchronous call 它看起来像一个大阅读,但如果你想编写一个处理异步代码的 JavaScript 程序(这就是你想要做的),100% 需要知识)。您的问题没有明确的答案,因为需要更多上下文才能更好地了解最佳选择是什么。我建议您阅读我发送的链接以尝试获得更好的想法,您可以在这里使用 Promises 来提供帮助,这也解释了链接

标签: javascript node.js express constants


【解决方案1】:

当您重新分配 totalRecords 变量时,将其设为 let 而不是 const

【讨论】:

  • 但得到未定义的值
【解决方案2】:

在 javascript 中,您不能在声明之后为 'const' 赋值。您必须在声明行将值分配给 const。

如果您确实需要稍后声明该值,那么最好使用 'let'

【讨论】: