javascript - Nodejs延迟更新变量
问题描述
我不明白为什么我的变量更新这么晚。我继续搜索,他们说我应该同步/等待它,但我不知道该怎么做。
这是我的代码:
Config.js
global.sql = require ('mssql');
global.dbConfig = {
server: "#",
user: "#",
password: "#",
port: 1433,
options: {
encrypt: false,
enableArithAbort: false
}
};
这是存储函数的文件:
test.js
require('./Commands/Config');
global.Bound_Account = function Bound_Account(ID, username) {
ID = BigInt(ID);
let conn = new sql.ConnectionPool(dbConfig);
let req = new sql.Request(conn);
conn.connect(function (err) {
if (err) throw err;
var query = `EXEC dbo.usp_Bound ${ID}, ${username}`
req.query(query, function (err, recordset) {
if (err) throw err;
else
var Code = (recordset.recordset[0].Code);
switch(Code){
case '-2':
bound_response == "Account not found, please try again.";
break;
case '0':
bound_response = ("Verification Code sent successfully.");
break;
case '1':
bound_response = ("Account is already verified.");
break;
case '2':
bound_response = ("Verification Code sent successfully");
break;
default:
bound_response = ("Error occurred, please try again. Error Code: "+response);
break;
}
});
req.close;
conn.close;
});
}
这是我的默认文件,或索引
global.bound_response = null;
....####....
bound_account(id,param1);
console.log('bound_response: '+bound_response);
.....####....
所以事情是这样的:
/bound James (So James is the param1, while id is for the ID of user who use the command, so let us say it is 10)
bound_response: null (It should be "Verification Code sent successfully.")
/bound sahdjashdj (I entered random name so the response should be "Account not found, please try again.")
bound_response: Verification Code sent successfully.
/bound James
bound_response: Account not found, please try again
这些是我的代码的摘录,对不起,如果我不能把所有的东西都放好。但是如果您需要更多,您可以在下面发表评论。
所以我的问题是延迟更新bound_response。
解决方案
您可以使用async/await
这样您的代码将等到您从数据库中获取结果。
//example
async function example1 () {
const mssql = require('<path>');
const conn = await mssql.createConnection({ database: test });
let data = await req.query(query, function (err, recordset) {
//procressing with data
}
}
推荐阅读
- swift - 在 UITableView 数据上保存订单
- c# - 使用模型从 cshtml 调用函数到 cshtml.cs
- slider - 如何使用带有缩略图滑块的光滑滑块制作自定义滑块?
- javascript - 如何隐藏表格标题列
- javascript - 在生成表格以划分从 jquery 生成的意外代码时
- java - 事件驱动在 Spring MVC 中继续请求线程执行
- jquery - 如何使用jquery在按钮单击时显示和隐藏div
- java - 替换Java中的正则表达式匹配
- asp.net-core - 使用 grant_type 作为密码在 .net 核心 Web API 中验证并获取 Azure AD 令牌
- meteor - 我应该使用什么“逻辑查询运算符/s”来合并两个单独的查询?