Skip to content

Instantly share code, notes, and snippets.

@moredip
Created April 9, 2012 16:35
Show Gist options
  • Save moredip/2344608 to your computer and use it in GitHub Desktop.
Save moredip/2344608 to your computer and use it in GitHub Desktop.
Alternative functional approach to dealing with the async pyramid. This is a response to http://wekeroad.com/2012/04/05/cleaning-up-deep-callback-nesting-with-nodes-eventemitter/
validate = (customer, next)->
console.log 'validating...'
#VALIDATE HERE
next()
insert = (customer, next)->
console.log 'inserting...'
# insert into DB (asynchronously of course), and then call...
next()
sendEmail = (customer, next)->
console.log 'sending email...'
# send email (asynchronously of course), and then call...
next()
registerCustomer = ( customer, successCallback )->
# WORKFLOW
afterValidate = (customer,next)-> insert( customer, afterInsert )
afterInsert = (customer,next)-> sendEmail( customer, afterEmail )
afterEmail = (customer,next)-> successCallback( customer )
validate( customer, afterValidate )
module.exports = registerCustomer
// A compiled version of the coffeescript, for those that don't like coffeescript
var insert, registerCustomer, sendEmail, validate;
validate = function(customer, next) {
console.log('validating...');
return next();
};
insert = function(customer, next) {
console.log('inserting...');
return next();
};
sendEmail = function(customer, next) {
console.log('sending email...');
return next();
};
registerCustomer = function(customer, successCallback) {
var afterEmail, afterInsert, afterValidate;
// WORKFLOW DEFINED HERE
afterValidate = function(customer, next) { return insert(customer, afterInsert); };
afterInsert = function(customer, next) { return sendEmail(customer, afterEmail); };
afterEmail = function(customer, next) { return successCallback(customer); };
// START WORKFLOW
return validate(customer, afterValidate);
};
module.exports = registerCustomer;
var registerCustomer = require('registerCustomer');
console.log('registering customer...');
registerCustomer('dummy customer data', function() {
return console.log('customer registered!');
});
@NReilingh
Copy link

Got here after googling Rob Conery's article. In lines 19-21, the (customer,next) parameters on the functions being defined are superfluous, no? The after_ functions are being called with next(), having no params passed in...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment