-1

I am using NodeJS postgresql client to fetch some data loop through it and give an output. I'm using ExpressJS together with postgresql client.

This is my code

    var main_data = some array of data
    var user_info = {}
    for (var key in result.rows) {
      var user = main_data[key].user

      client.query('SELECT name,age,address FROM users WHERE user_id = $1 LIMIT 1;' , [user], function(queryErr, result){
        var return_data = result.rows[0]
        user_info.name = return_data.name
        user_info.gender = return_data.gender
        user_info.address = return_data.address
        main_data[key].user_info = user_info
     })
    }

    done()
    res.json(main_data)
    return

However when I run this code I don't get a proper output. The userinfo is not pushed to the main_data. It just outputs main_data variable just as the beginning of the code.

It is not simple as the suggested duplicate Because the function sits inside a for loop so I can't just make the response call once the function is done. I have to wait till the whole loop is finished which may be 1000+ of loops to finish before I can make the response call.

So tell me how can I achieve it. What am I doing wrong and how can fix it? Thank you very much

rksh
  • 3,920
  • 10
  • 49
  • 68
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ram Jun 17 '16 at 18:38
  • But the problem is that the function is inside a loop so I can't return the data within the function. I have wait till the loop is finished. So it's not simple as making the response inside the client.query call. – rksh Jun 17 '16 at 18:39
  • You should checkout the nodejs postgres driver docs. You'll then realize that the callback function in which you have data occurs asynhronously, and therefore your res.json call is sending information that hasn't had the chance to be updated yet. – Paul Jun 17 '16 at 18:40

1 Answers1

1

I would use async.js for this, myself.

var rows = // your result.rows stuff.

function doTheQuery(item, callback){
   // your query logic here, calling the callback with the results
}

async.series(rows, doTheQuery, function(err){
   // handle any errors
}
Paul
  • 35,689
  • 11
  • 93
  • 122
  • Alternatively, you could also use promises. For this case, you could build an array of promises which each resolve with `user_info` and use `.all(promises)` (e.g. [RSVP.all()](https://www.npmjs.com/package/rsvp#arrays-of-promises)) to call them all serially. – Squirrel Jun 17 '16 at 19:57
  • I'm actually not a fan of promises, and feel like they're not solving things any better than properly architected callbacks. – Paul Jun 18 '16 at 14:17