【发布时间】: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。这就是为什么当你记录它时totalRecords是undefined。将console.log('::'+ totalRecords);和任何其他依赖于rows的代码移到回调函数中。 -
另请阅读:How to return the response from an asynchronous call 它看起来像一个大阅读,但如果你想编写一个处理异步代码的 JavaScript 程序(这就是你想要做的),100% 需要知识)。您的问题没有明确的答案,因为需要更多上下文才能更好地了解最佳选择是什么。我建议您阅读我发送的链接以尝试获得更好的想法,您可以在这里使用 Promises 来提供帮助,这也解释了链接
标签: javascript node.js express constants