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!
1 Answer 1
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);
}
}
);
}
-
\$\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– Maroshii2012年08月16日 12:47:53 +00:00Commented Aug 16, 2012 at 12:47 -
\$\begingroup\$ If you have a lot of nested callbacks your code can become unwieldy... \$\endgroup\$Oved D– Oved D2012年08月16日 17:42:22 +00:00Commented Aug 16, 2012 at 17:42