Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm making requests to Parse.com to 3 different objects that are needed to render a View. I'd like to know what's the general/best approach in cases like these in which there are multiple requests before actually handling the data.

Code:

    var Parse = require('parse-api').Parse;
    var parse = new Parse();

    exports.single = function() {
        parse.find('Class_1',params1,function(error,response1){
            parse.find('Class_2',params2,function(error, response2){
                parse.find('Class_3',params3,function(error3, response3){

                    // handle responses....
                    // render view....
                })
            })
        })
    }

Thanks!

share|improve this question

1 Answer

up vote 1 down vote accepted

Use Step.js or async.js to make this look cleaner. Step.js is simpler, but async.js gives you more flexibility.

Also, your function single needs to have a callback, and cannot return values since the functions it's invoking are not returning values.

Additionally, generally the data retrieval methods should be separate from the rendering methods.

With Step.js, this could look like:

 var Parse = require('parse-api').Parse,
    Step = require('step');
    var parse = new Parse();
exports.getAndRenderData = function(res, params1, params2, params3){
   getData(params1, params2, params3, function(err, data){
      if(err)
        throw err:
      else {
        res.render('viewname', data);
      }
   });
}

var getData = function(params1, params2, params3, callack) {
    var data = {}; 
    Step()(
        function getClass1(){
            parse.find('Class_1',params1, this);
        },
        function getClass2(err, class1data){
           if (err) throw err;
           data.class1 = class1data;
           parse.find('Class_2',params2, this);
        },
        function getClass3(err, class2data){
           if (err) throw err;
           data.class2 = class2data;
           parse.find('Class_3',params3, this);
        },
        function callbackWithAll(err, class3data){
           if (err) callback(err); 
           else {
             data.class3 = class3data;
             callback(null, data);
           }
        }
    );
}
share|improve this answer
single is not returning anything, it just renders the view. I'll look into Steps.js. Btw, What's the benefit of doing this? – Maroshii Aug 16 '12 at 12:47
If you have a lot of nested callbacks your code can become unwieldy... – Oved D Aug 16 '12 at 17:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.