Skip to content

Instantly share code, notes, and snippets.

@jplhomer
Created May 22, 2014 13:28
Show Gist options
  • Save jplhomer/7ce16373c0db942a1ca9 to your computer and use it in GitHub Desktop.
Save jplhomer/7ce16373c0db942a1ca9 to your computer and use it in GitHub Desktop.
How do I use promises in NodeJS?
/*
* This is a NodeJS app using the official MailChimp API wrapper.
* I want to grab this data and display it in a custom view, but without a giant callback-y mess. Ideas?
*/
exports.view = function(req, res){
mc.campaigns.list({campaign_id: req.params.id}, function(campaignData) {
var campaign = campaignData.data[0];
mc.reports.summary({cid:req.params.id}, function(reportData) {
mc.lists.list({ list_id: campaignData.list_id }, function(listData) {
mc.reports.clicks({ cid:req.params.id }, function(clickData){
// I also want to hit another endpoint to grab details about unsubscribes/reasons before returning.
res.render('reports/view', { title: 'Report for ' + campaign.title, campaign: campaign, report:reportData, list:listData.data[0], clicks:clickData });
});
});
}, function (error) {
console.log(error);
if (error.name == "Campaign_DoesNotExist") {
req.session.error_flash = "The campaign does not exist";
} else if (error.error) {
req.session.error_flash = error.code + ": " + error.error;
} else {
req.session.error_flash = "An unknown error occurred";
}
res.redirect('/reports');
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment