首页 > 解决方案 > 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。

标签: javascriptnode.jsasynchronousasync-await

解决方案


您可以使用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
  }
}


推荐阅读