I'm running the following code on Node.js
and I am trying to use mysql
with nodejs
: trying to run the query: select numbers from TABLE
. The result comes out as:
"undefined"
function getNumbers()
{
cio.query("SELECT numbers FROM rooms WHERE durum='1'", function(err, result)
{
if (err)
throw err;
else
result[0].numbers;
});
}
var kar = getNumbers();
console.log(kar);
So, what should I do ? Please help.
Functions getNumbers()
and the function called inside it don't return any values, so the result will always be undefined
.
Other than that you need to handle the asynchronous nature of the function:
wait until the database query is complete before returning a value .
You can do this by using a callback function .
Example below:
function getNumbers(callback) {
cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}
getNumbers(function (result) {
console.log(result);
});
I don't know if your question depends on your console.log
but your function has no return value. So when you have no return then it's undefined
.
function getNumbers() {
return 'test';
}
var kar = getNumbers();
console.log(kar);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.