1

I have a set of nested queries with express/mongoose, pretty much like so:

app.get(..., function(...) {

   Schema1.query(..., function(..., res1) {

      for ( var key in res1 ) {
           Schema2.query(..., function(..., res2) {
             data[key].appendedAttribute = res2.somedata;
            });
      }

      res.render(..., data);
   });

});

Which doesnt work, that is, appendedAttribute is never appended to the dataset. What am I doing wrong?

1
  • 1
    That's not how asynchronous programming works Commented Nov 13, 2011 at 22:49

2 Answers 2

2

Using after

app.get(..., function(...) {
    Schema1.query(..., function(..., res1) {
        var cb = after(Object.keys(res1).length, function () {
            res.render(..., data);    
        });

        for (var key in res1) {
            Schema2.query(..., function(..., res2) {
                data[key].appendedAttribute = res2.somedata;
                cb();
            });
        }
    });
});

Basically you must only fire the res.render call after the second query has finished.

Sign up to request clarification or add additional context in comments.

2 Comments

Aren't you suppose to call cb() only after all the queries get executed..? (thus just once)
@alessioalex cb has to called n times. before it continues. the n is the first parameter to after. i.e. the amount Schema2 queries he makes.
0

Using Step:

app.get(..., function(...) {
  var data;
  Step(
    function first_query() {
      Schema1.query(...,this);
    },
    function multiple_queries(err, res1) {
      for (var key in res1) {
        Schema2.query(..., function(..., res2) {
          data[key].appendedAttribute = res2.somedata;
          this.parallel(); // make sure callback gets executed only after all the queries are executed
        });
      }     
    },
    function render() {
      res.render(..., data);
    }
  );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.