I have a node app hitting postgres, in one of my functions I will need to be able to query many tables to get data to assemble for my json to send back. What is the best way to do this given the nature of nodejs, and I would like to avoid multiple levels of nested callbacks? I have been hunting around, but just am not grokking this concept well.
Asked
Active
Viewed 2,612 times
1
-
Perfectly explained in this answer http://stackoverflow.com/a/6604036/1520671 – Salman Jul 01 '14 at 14:51
-
have you tried wait.for? https://github.com/luciotato/waitfor – Lucio M. Tato Sep 04 '14 at 21:38
1 Answers
0
It depends on your queries nature, if you need them execute one after another, or in parallel, gathering all the results/errors in one place.
Typical approach to avoid nested callback hell is to use async library (and series, parallel functions) or it's analogs.
It would be something like this:
async.parallel([
function(callback) {
db.query(..., callback);
},
function(callback) {
db.query(..., callback);
}
],
function(err, results) {
// results is array containing array of results of your queries
});
Please refer to async documentation for more info and examples.

Yaroslav Pogrebnyak
- 1,117
- 9
- 22