gpt4 book ai didi

javascript - 全局变量在 NodeJS 中不起作用未定义

转载 作者:太空宇宙 更新时间:2023-11-04 03:01:43 26 4
gpt4 key购买 nike

是否可以在node.js函数中定义全局变量?

我想在其他函数中使用 ko 变量(在 getNumbers 函数中声明)

function getNumbers(callback) {
result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}

var ko = getNumbers(function (result) {

console.log(result)
});


var zo = ko;

“未定义”

46,16,55,12,74,48,77,42,4,29,14,81,13,35,39,85,7,54,27,66,41,9,17,82,31,21,57,79,62,56,11,49,3,33,64,8,83,88,61,18,58,63,51,90,22,71,67,69,75,6,2,34,30,25,38,28,68,5,50,15,87,19,65,36,45,24
C:\wamp64\www\node\st\rooms.js:497
var datadad = zo[Math.floor(Math.random()*zo.length)];
^

TypeError: Cannot read property 'length' of undefined
at sayiver (C:\wamp64\www\node\st\rooms.js:497:54)
at Timeout._onTimeout (C:\wamp64\www\node\st\rooms.js:513:5)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)

最佳答案

这是对您的代码的快速修复。如前所述,由于您不从函数返回此值,因此您必须在回调内处理此逻辑。另外,即使您返回一个值,ko 仍然会未初始化(当您尝试将其值分配给 zo 时),因为您使用异步操作从数据库获取某些内容,并且在分配之前不会等待数据。

function getNumbers(callback) {
result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}

var ko;
var zo;

getNumbers(function (result) {
ko = result;
console.log(result);
zo = ko;
});

这是一个代码示例,其中 zo 仍然是未定义的(当然,假设该函数不同步):

function getNumbers(callback) {
result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}

var ko;

getNumbers(function (result) {
ko = result;
console.log(result);
});
var zo = ko; //Not good!

关于javascript - 全局变量在 NodeJS 中不起作用未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002630/

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