DEV Community

Jota Feldmann
Jota Feldmann

Posted on • Edited on

3

Tricky async declarations

Imagine the following code, using Express and Sequelize:

app.get('/', async (_, res) => {
  const result = await sequelizeModel.getStuff()[0]
  return res.status(200).send(result)
}

In simple words: given an endpoint, it will execute a query on the database and return the result.

But there's a small gotcha: that code works but doesn't return the results, because at the time of the promise creation, the [0] is not available/ready.

Only after the promise/async is fulfilled, the Sequelize object exists.

Working code:

app.get('/', async (_, res) => {
  const result = await sequelizeModel.getStuff()
  return res.status(200).send(result[0])
}

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →