Reputation: 121
I have a complex chain of async callbacks and during any point in the chain, if there's an error, I'd like to render a Jade template with the error message.
In the function partnerErr below, is it possible to respond with a template without the original response object?
app.post('/dashboard/partners/create', function (req, res) {
console.log( req.body );
ParseUtils.doesUserExist(
req.body.partnerEmail,
function() { ShopifyUtils.doesPartnerExist( req.body.partnerShopSlug,
function() { ParseUtils.createUser( req.body,
function() { ShopifyUtils.createPartner( req.body,
res.send( ' all good. parse and shopify passed. user created. '),
partnerErr
); },
partnerErr
); },
partnerErr
);
},
partnerErr
);
});
function partnerErr(err) {
console.log( 'rendering partner error' );
app.render('admin/partnersCreate', { error : err }, function(err, html) {
console.log('html', html);
});
}
Upvotes: 1
Views: 222
Reputation: 7863
Firstly, I would take a look at https://github.com/caolan/async to clean up your series of async calls. That many nested is almost unreadable. It looks like series
or waterfall
would suite your needs here. This would also drastically cut down the number of times you need to write partnerErr
and move all of the error checking logic into one place.
That being said, why not just pass res
into partnerErr
and use res.render
? Am I understanding your question correctly?
UPDATE
I would strongly encourage you to consider rewriting this as I said above, however, if you want to leave it alone, you could do something like this:
app.post('/dashboard/partners/create', function(req, res) {
console.log(req.body);
ParseUtils.doesUserExist(
req.body.partnerEmail,
function() {
ShopifyUtils.doesPartnerExist(req.body.partnerShopSlug,
function() {
ParseUtils.createUser(req.body,
function() {
ShopifyUtils.createPartner(req.body,
res.send(' all good. parse and shopify passed. user created. '),
partnerErr(res)
);
},
partnerErr(res)
);
},
partnerErr(res)
);
},
partnerErr(res)
);
});
function partnerErr(res) {
return function(err) {
console.log('rendering partner error');
res.render('admin/partnersCreate', {
error: err
});
}
}
Another option would be to move the partnerErr
function into the same scope as the app.post
and just have access to the res
variable. I'm not sure how decoupled the partnerErr
truly is based just on this snippet.
Upvotes: 1