-1

I have a function in this way

function con(){
    database.connect(con, (err, con) => {
        conn.query("select * from person", (err, rs) => {
            console.log(rs)--->result
            return rs
        })
    }
}
var val = con()
console.log(val) // --> Undefined

After lot of searching came to know we cant return a value from callback.Done this

function con(fn){
    database.connect(con, (err, con) => {
        conn.query("select * from person", (err, rs) => {
            console.log(rs) // --> result
            fn(rs)
        })
    }
}
var val = con(function(rs) {
    console.log(rs) // --> result
    return rs
})

console.log(val) // --> Again undefined

I want to use the rs in another method and should return it in the resolver of the graphql How to return the value from the above and use it in another function

  • Does this answer your question? [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) – Nick Parsons Mar 03 '21 at 09:50
  • No i want to again return the value from the con as val it is undefined – G Bulli Swamy Reddy Mar 03 '21 at 09:57
  • You can't, you'll need to use the value in the callback, or use a Promise like mentioned in the link. `console.log(val)` will run before your `connect` callback function is called, so the only way to know when `val`/`rs` is available is to use a callback/Promise – Nick Parsons Mar 03 '21 at 10:02

1 Answers1

0

So, the thing you need to understand clearly -- when you return, you return from current function.

In the example:

var val = con(function(rs) {
    console.log(rs) // --> result
    return rs
})

you return rs from anonymous callback function. But con does not return anything.

I would recomend you to use async/await, as far as I got you use pg or mysql.

const connection = await database.connect(connectionOptions)
const result = await connection.query('select * from person')
console.log('Result:', result)
hazer_hazer
  • 136
  • 1
  • 7
  • Thanks for the reply but i had a callback to the connect and after succesfull connect i need to query the results for query again there is an callback how to convert it to the async await – G Bulli Swamy Reddy Mar 04 '21 at 06:23
  • @GBulliSwamyReddy, if you want to check for errors on `connection`, or on `query` -- just put them in `try-catch` blocks. That's it. And your code will be more flatter than with callbacks. – hazer_hazer Mar 04 '21 at 10:48
  • Example: `let connection; try { connection = await database.connect(); } catch (error) {...}` – hazer_hazer Mar 04 '21 at 10:49