Last active
July 11, 2023 02:59
-
-
Save darrenscerri/5c3b3dcbe4d370435cfa to your computer and use it in GitHub Desktop.
A very minimal Javascript (ES5 & ES6) Middleware Pattern Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Middleware = function() {}; | |
Middleware.prototype.use = function(fn) { | |
var self = this; | |
this.go = (function(stack) { | |
return function(next) { | |
stack.call(self, function() { | |
fn.call(self, next.bind(self)); | |
}); | |
}.bind(this); | |
})(this.go); | |
}; | |
Middleware.prototype.go = function(next) { | |
next(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Middleware { | |
use(fn) { | |
this.go = (stack => next => stack(fn.bind(this, next.bind(this))))(this.go); | |
} | |
go = next => next(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by: https://github.com/kolodny/exercises/tree/master/middleware | |
var middleware = new Middleware(); | |
middleware.use(function(next) { | |
var self = this; | |
setTimeout(function() { | |
self.hook1 = true; | |
next(); | |
}, 10); | |
}); | |
middleware.use(function(next) { | |
var self = this; | |
setTimeout(function() { | |
self.hook2 = true; | |
next(); | |
}, 10); | |
}); | |
var start = new Date(); | |
middleware.go(function() { | |
console.log(this.hook1); // true | |
console.log(this.hook2); // true | |
console.log(new Date() - start); // around 20 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by you,I update my
pipeline.js
,like this:util.js
pipeline.js