i am building a twitter like app. my Node server retrieves data from the sql database using knex. i have an issue with the code at the endpoint that's supposed to get the posts ('emails' is an array):
app.post('/posts', (req, res) => {
const { emails } = req.body;
let arr = [];
emails.forEach(email => {
db('*')
.from('posts')
.where('email', '=', email)
.then(result => {
arr.push(result)
})
})
res.json(arr)
})
when i console log the 'result' inside the promise i'm getting the desired post, but i get an empty array at the response. i'm assuming the problem has somewhat to do with the fact that it's a promise? i've tried to somehow turn this into a async function but didn't succeed in making it work.
Every one of those db
calls return a promise, which you currently ignore. And because you're not waiting for them, your res.json
call runs before the arr.push
calls.
forEach
to map
db
calls, so now I have an array of promises.Promise.all
then
will get the results of all those promises in an array, so no need for the arr
array anymore.Code:
Promise.all(
emails.map(
email => db("*").from("posts").where("email", "=", email)
)
).then(results => {
res.json(results);
});