-1

I'm trying to set a variable to a function that returns a boolean. However, I can't seem to achieve this. Is this where you use async functions?

Here is my code: (NodeJS)

function getNumbers() {

    return client.query(query, (error, result) => {
        if (error) {
        console.log(error)
        return false
        } else if (result.rows.length) return true
        else return false
    })
}

app.post('/receiveSMS', (request, response) => {
    let doesUserExist = getNumbers()
    console.log(doesUserExist)
}

The output that I get when console logging is undefined.

Thanks for the help!

Whatty
  • 69
  • 1
  • 5
  • 1
    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) – Patrick Roberts Mar 07 '18 at 19:14

1 Answers1

1

client.query will not return the result, instead when the query is executed it will invoke the callback method.

function getNumbers(callback) {

    return client.query(query, callback)
}

app.post('/receiveSMS', (request, response) => {
    let doesUserExist
    getNumbers((error, result) => {
        if (error) {
           console.log(error)
           doesUserExist = false
        } else if (result.rows.length) {
            doesUserExist = true 
        } else {
           doesUserExist = false
        }

        console.log(doesUserExist)
        // send response
    })

}
Khlbrg
  • 149
  • 1
  • 6