0

I have an indentation problem in my Coffee Script!!

I'm asking myself how put these lines of code so that they run smoothly and don't skip stuff. The impact is that the array friendsCollection is empty, when I want to use it in my view.

I guess the problem is coffee script (javascript) itself (because it works asynchronously) but I have no idea how to go about that.

Now, this is the code:

app.get '/', (req, res) ->
  brain = req.session
  if brain.userId
    friendsCollection = []
    data.serialize ->
      data.each "select rowid as id, * from friends where userId='#{brain.userId}'", (err, row) ->
        if not err
          if row isnt undefined
            friend =
              name: row.name
              email: row.email
              phone: row.phone
              location: row.location
              relationship: row.relationship
              notes: row.notes
            friendsCollection.push friend
      res.render 'app/index',
        id: brain.userId
        friendsCollection: friendsCollection
  else
    res.render 'notAllowed'

I would be happy if someone could fix this code (a little bit)!

Timo
  • 261
  • 5
  • 18
  • This isn't an indentation problem. This is an async problem. You need to not call res.render until all your async operations are complete. Personally, I'd use a promise-based interface to the database and use `Promise.all()` or Bluebird's `Promise.map()` to know when all the async operations are done and I could then call `res.render()`. – jfriend00 Nov 06 '16 at 15:16
  • Thanks, could you provide an conceptual code example ??! – Timo Nov 06 '16 at 15:57
  • Multiple examples here for how you accumulate the results of multiple async operations: http://stackoverflow.com/questions/32799672/node-js-how-to-set-a-variable-outside-the-current-scope/32799727#32799727 – jfriend00 Nov 07 '16 at 03:52

0 Answers0