Search code examples
node.jspostgresqles6-promiseknex.js

pushing to array when recieving value from Knex


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.


Solution

  • 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.

    1. I changed forEach to map
    2. I returned the promises from the db calls, so now I have an array of promises.
    3. I waited for all those promises with Promise.all
    4. Its then will get the results of all those promises in an array, so no need for the arr array anymore.
    5. Then I can send the response.

    Code:

    Promise.all(
      emails.map(
        email => db("*").from("posts").where("email", "=", email)
      )
    ).then(results => {
      res.json(results);
    });