如何将NodeJS查询分配给全局数组变量



我是Javascript的新手,目前正在使用MySQL服务器和NodeJS进行一个项目。

我遇到的问题是,当我试图将MySQL查询的结果推送到全局数组时,数组返回时完全为空。是我做错了什么,还是有人可以向我解释一些额外的步骤?

相关代码:

var itemList = [];
var siteList = [];
function getItems(){
con.connect(function(err) {
try{
if (err) throw err;
con.query("SELECT DISTINCT ProductURL FROM products;", function (err, result, fields) {
if (err) throw err;
for (i=0; i<result.length; i++){
itemList.push(result[i].ProductURL);
}
});
} finally{
con.end();
}
});
async function another_function() {
//Does some stuff with the information in the itemList array and inputs to siteList
}
async function anofuncV2() {
//does more stuff with the information provided by another_function
}
let result = await getItems();
itemList.forEach(another_function);
anofuncV2(siteList);

连接本身很好,并且在阵列推送返回正确信息后立即进行了测试和console.log。

附加说明:我确实需要它作为一个全局数组,以便其他功能正常工作,我知道我可以把它放在推送后工作,但这不是我想要的

编辑1:我知道代码是异步的,但无论我怎么研究,异步代码的整个概念都让我感到困惑。所以,如果有人能给出一个简单的解释,那就太好了。

我的理解:

  • 它与同步代码同时运行,导致其他代码在信息输入数组之前运行

这就是异步代码在JavaScript中的工作方式。

附加说明:我确实需要它作为另一个的全局数组功能正常工作,我知道我可以把它推到工作,但这不是我想要的

您需要等待getItems函数的结果,并且只有在执行完之后才能继续执行。

理想情况下,应该是这样

var itemList = [];
async function getItems(){
return new Promise((resolve, reject) => {
con.connect(function(err) {
try {
if (err) throw err;
con.query("SELECT DISTINCT ProductURL FROM products;", function (err, result, fields) {
if (err) throw err;
for (i=0; i<result.length; i++){
itemList.push(result[i].ProductURL);
}
});
resolve(itemList); 
} finally {
con.end();
reject(undefined) // handle error
}
});
})
}
let result = await getItems(); // this will print values inside of itemList array.

最新更新