Skip to content

Instantly share code, notes, and snippets.

@enten
Last active August 22, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enten/d0019859cb39fc643b18eacb6f0bee22 to your computer and use it in GitHub Desktop.
Save enten/d0019859cb39fc643b18eacb6f0bee22 to your computer and use it in GitHub Desktop.
Javascript Middleware Pattern
function nextify (middlewares, callback) {
return (...args) => {
middlewares.slice(0).reverse().reduce((next, fn) => {
return () => fn(...args, (err) => {
if (err) {
return callback(err)
}
next()
})
}, callback)()
}
}
/** Usage */
const next = nextify([
(a, b, next) => {console.log('CP1', a, b); next()},
(a, b, next) => {console.log('CP2', a, b); next(new Error('fake error'))},
(a, b, next) => {console.log('CP3', a, b); next()},
], (err) => console.log('DONE', {err}))
next('A', 'B')
/** Output */
// CP1 A B
// CP2 A B
// DONE { err:
// Error: fake error
// at nextify (/home/steven/code/nextify.js:17:51)
// at /home/steven/code/nextify.js:4:20
// at fn (/home/steven/code/nextify.js:9:9)
// at nextify (/home/steven/code/nextify.js:16:46)
// at /home/steven/code/nextify.js:4:20
// at /home/steven/code/nextify.js:11:17
// at Object.<anonymous> (/home/steven/code/nextify.js:21:1)
// at Module._compile (module.js:571:32)
// at Object.Module._extensions..js (module.js:580:10)
// at Module.load (module.js:488:32) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment