0

I have following code:

const get = (ip,key) => {
mysql.query(`SELECT content FROM sessions WHERE ip = "${ip}" AND name = "${key}" ORDER BY id DESC LIMIT 1`,(err,result) => {
    if(err) throw err
    console.log('Callback:',result[0].content)
    return result[0].content
})
}

console.log('Return:',get('10.0.0.9','test'))

It produces following output:

Return: undefined
Callback: test content

Why doesn't my function return anything?

Tobi696
  • 448
  • 5
  • 16
  • because it is not the `get` function that returns the value. The callback is a different function, – EJK Jan 27 '19 at 17:10

1 Answers1

1

The value "test content" is what's actually returned by the handler (or callback) you pass to mysql.query().

Your function get actually do not return anything.

You are dealing with an asynchronous function. There is several way to solve your problem.

Simplest one, would be to pass a third argument to your get function, a callback function an call it in your mysql handler. Something like:

const get = (ip,key,callback) => {
mysql.query(`SELECT content FROM sessions WHERE ip = "${ip}" AND name = "${key}" ORDER BY id DESC LIMIT 1`,(err,result) => {
    if(err) throw err
    console.log('Callback:',result[0].content);
    // Call you custom callback here to forward result
    callback( result[0].content );
})
}

get('10.0.0.9','test', (result) => console.log('Return:', result));

An other approach, more modern would be to use Promise

And the most 'up to date' solution would be to use a async/await

Clement
  • 3,860
  • 4
  • 24
  • 36