Tricky async declarations
Jota Feldmann
Posted on January 16, 2020
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])
}
💖 💪 🙅 🚩
Jota Feldmann
Posted on January 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.