Nodejs 将值分配给全局常量变量



我在nodejs中有一个函数,我从SQL数据库获取客户,我需要将其分配给变量以使用它进行进一步处理。

下面是我的代码:

function getCustomers() {
var i;
var conn = new sql.Connection(dbConfig);
var _customerName;
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT CustomerName FROM CUSTOMERS").then(function (recordset) {
//console.log(recordset);
for (i = 0; i <= recordset.length; i++) {
_customerName =  String(recordset[i].NAMECUST);
}
return _customerName;
// conn.close();
})
.catch(function (err) {
console.log(err);
//conn.close();
});
})
.catch(function (err) {
console.log(err);
});
finalize(obj, function () {
return _customerName;
});

}
//console.log();
const categories = {
"headquarters": {
"category": "headquarters",
"suggestion": "Headquarters",
"facts": [
"Customer 1",
"Customer 2",
"Customer 3"
],
"factPrefix": "Okay, here's a Customer fact."
}

};

我无法从函数中检索值并将其分配给类别变量。

在顶部声明一个变量 变量类别 = {};

并在方法 GetCustomers(( 中赋值。

但这不是正确的方法,你必须使用回调方法并在回调方法中返回数据。

我认为您需要将赋值代码行推送到回调函数中。 您的代码可能如下所示:

const categories = {
"headquarters": {
"category": "headquarters",
"suggestion": "Headquarters",
"facts": [],
"factPrefix": "Okay, here's a Customer fact."
}
function getCustomers() {
var i;
var conn = new sql.Connection(dbConfig);
var _customerName;
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT CustomerName FROM CUSTOMERS").then(function (recordset) {
//console.log(recordset);
for (i = 0; i <= recordset.length; i++) {
categories.headequaters.facts.push(recordset[i].NAMECUST)
}
})
.catch(function (err) {
console.log(err);
//conn.close();
});
})
.catch(function (err) {
console.log(err);
});
finalize(obj, function () {
return _customerName;
});
}
};

最新更新