Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple example showing how to chain functions similar to how middleware is chained in express.js
// simple example of how to create a function that calls a middleware chain, similar to express middleware
var req = {type: "req"};
var res = {type: "res"};
// 3 middlewares
var first = function(req, res, next) {
req.first = true; //easy way to verify that all have been executed
res.first = true;
return next();
var second = function(req, res, next) {
req.second = true;
res.second = true;
return next();
// this one is last
var last = function(req, res) {
console.log('End of middleware reached');
console.log('req', req);
console.log('res', res);
// Starts with last function in the array, and binds params (req,res) and "next" fn if available
// Iterates through fns array backwards binds to the next until it reaches the beginning of the fns array
// @params you want to pass to each one
// @functions in the middleware chain
// @returns a function that starts it all
function chainMiddleware(params, ...fns) {
return fns.reduceRight(function(prev, curr) {
return curr.bind(null, ...params, prev); // bind req,res, next for last() then second() then first()
}, null) // null forces req,res to be bound to last() properly (w/o next)
var start = chainMiddleware([req, res], first, second, last);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment