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!

asked Aug 16, 2012 at 10:28
\$\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);
 }
 }
 );
}
answered Aug 16, 2012 at 11:55
\$\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\$ Commented Aug 16, 2012 at 12:47
  • \$\begingroup\$ If you have a lot of nested callbacks your code can become unwieldy... \$\endgroup\$ Commented Aug 16, 2012 at 17:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.