-1

there is a certain function from which it is necessary to pull out value.

function func () {
  let a

  sql = `SELECT * FROM ...`
  db.query(sql, function (err, results) {
    if (err) throw err
    a = ...
  })
  return a
}
func()

let per = func()

But all the time undefined. This is solved by async / await ?

  • The function inside the query call is a callback function, which means it is executed *after* the query has completed. You cannot use `return` with asynchronous methods. Instead you should have the code you want to execute afterwards in a function and call that function (with the results as a parameter) from inside the callback. – Reinstate Monica Cellio May 02 '19 at 18:05

1 Answers1

0

You need a callback function (or a promise)

function func(cb) {
  sql = `SELECT * FROM ...`
  db.query(sql, function (err, results) {
    if (err) throw err
    cb(results)
  })
}

func((a) => {
  console.log(a); // results of the query
})
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337