0

In my express.js app, I would like to encapsulate my async database call into reusable function "getPerson(id)". Like so...

function getPerson(id) {
  db.get(
      `SELECT * FROM People WHERE id = ${id};`,
      (error, row) => {
        if (error || !row) {
          return false
        } else {
          return row.name
        }
      }
    )
}

But how can I "await" result from this function inside express.js request route block of code? Like so...

app.get('/person/:id', (req, res) => {
  const person = getPerson(req.params.id) // wait for this, but how?
  if (person) {
    res.status(200).send(person)
  } else {
    res.sendStatus(400)
  }
})

I have tried different combination of using async/await keywords in above code samples, but not sure how that works. Then I also read in express.js docs that async/await keywords are not even supported in express version <5. Above node.js examples use express.js 4.x and sqlite3 5.x modules. Thanks for the help.

bagatov
  • 1
  • 1
  • "Then I also read in express.js docs that async/await keywords are not even supported in express version <5" — That's irrelevant since you're looking for asynchronous functionality in whatever `db` is. – Quentin Jul 15 '22 at 10:03
  • Did you try making the express handler an async function and adding await before `getPerson` – me.nkr Jul 15 '22 at 10:49
  • I solved it. But since I am new here I am not sure if should I delete the question, edit the question, or just write the comment which I am doing right now. Anyway, I have used "async/await" keywords as @me.nkr suggested (thanks) but this time I have also returned promise in my "getPerson" function (I did not know that before). And also I have used try/catch logic in my express function handler so rejected promise could be handled. I would provide working code, but not enough characters left. – bagatov Jul 15 '22 at 12:44
  • @bagatov you can post how you solved it as an answer – me.nkr Jul 26 '22 at 03:32

0 Answers0