1
\$\begingroup\$

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!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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);
           }
        }
    );
}
\$\endgroup\$
2
  • \$\begingroup\$ single is not returning anything, it just renders the view. I'll look into Steps.js. Btw, What's the benefit of doing this? \$\endgroup\$
    – Maroshii
    Aug 16, 2012 at 12:47
  • \$\begingroup\$ If you have a lot of nested callbacks your code can become unwieldy... \$\endgroup\$
    – Oved D
    Aug 16, 2012 at 17:42

Your Answer

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

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