0

I am learning node.js.

The problem occurred when we used postgreSQL to create a function that retrieves data from a DB and returns the retrieved values.

The source is below.

findForLogin(email: string, password: string): any {
    const query = `
      SELECT 
      *
      FROM users
      WHERE true
        AND email = $1
        AND password = $2 
    `

    let user: any = {}
    this.pool.query(query, [email, password], (err, res) => {
      user = res.rows
      console.log('inner', user)
    })

    console.log('outer', user)
    return user
  }

}

Checking the log (console.log('outer', user)), the return value of the function is empty. The log of asynchronous processing (console.log('inner', user)) is output after that, and the user data is properly stored here.

As a countermeasure, I tried to return the user data after two seconds of sleep, but the result was the same.

What is the cause? What is the solution?

thank you

youkichi
  • 23
  • 5

0 Answers0