gpt4 book ai didi

mysql - Node js数组值访问问题

转载 作者:行者123 更新时间:2023-11-29 10:17:13 33 4
gpt4 key购买 nike

我有数组,我想将查询结果存储在数组中,下面是代码

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
if (err) throw err;
button_settings.push(result);
});
console.log(button_settings);

它显示[]我想要存储的结果。

最佳答案

您正在查询本质上是异步的数据库,因此 console.log 不会等待 con.query 的结果,并在之后立即执行。因此,您会打印出 [] 。但是,如果查询完成后 result 中有记录,那么如果将 console.log(button_settings); 放入 中,您将在控制台中打印数组>con.query 函数如下:

将代码更改为

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
if (err) throw err;
button_settings.push(result);
console.log(button_settings); //console after the query completes
});

因此,为了使流程像同步一样工作,您将使用 button_settings 的值,创建一个像这样的私有(private)函数,

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
if (err) throw err;
button_settings.push(result);
_processButtonSettings();
});

//put all your code related to button_settings here
function _processButtonSettings(){
console.log(button_settings);
//and more code...
}

关于mysql - Node js数组值访问问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953824/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com