0

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.

Bharat
  • 5,869
  • 4
  • 38
  • 58
Mert Fırat
  • 15
  • 2
  • 8
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Keith Dec 31 '18 at 12:06

2 Answers2

0

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);
});
Laurens Deprost
  • 1,653
  • 5
  • 16
  • Thanks for your help ... I tried but I get the "undefined" error again ... :( – Mert Fırat Dec 31 '18 at 12:01
  • The function `getNumbers` and the function inside it should **both** return a value. I've included an example in my answer. – Laurens Deprost Dec 31 '18 at 12:03
  • You can't synchronously return an asynchronous method, look at marked dupe. – Keith Dec 31 '18 at 12:11
  • Updated answer. – Laurens Deprost Dec 31 '18 at 12:21
  • this time I'm getting a different erro. I'm very sorry. " _ended: false, _timeout: undefined, _timer: Timer { _object: [Circular], _timeout: null }, sql: 'SELECT numbers FROM rooms WHERE durum=\'1\'', values: undefined, typeCast: true, nestTables: false, _resultSet: null, _results: [], _fields: [], _index: 0, _loadError: null, _connection: Connection { _events: [Object: null prototype] { error: [Array] }, _eventsCount: 1, _maxListeners: undefined, config: ConnectionConfig { host: 'localhost', – Mert Fırat Dec 31 '18 at 12:25
  • Can you share the code you used that produced that error? – Laurens Deprost Dec 31 '18 at 12:40
0

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);
René Höhle
  • 26,716
  • 22
  • 73
  • 82