Last active
December 28, 2017 03:52
-
-
Save jackfarrington/c250cb4eaa92337ed9c0 to your computer and use it in GitHub Desktop.
NodeJS pipelining module
This file contains hidden or 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 Chain { | |
constructor() { | |
this.chain = [] | |
} | |
use(handler) { | |
this.chain.push(handler) | |
return this | |
} | |
handle(context) { | |
return new Promise((resolve, reject) => { | |
const handlers = this.getChain()[Symbol.iterator]() | |
function getHandler(item) { | |
return err => { | |
if (err) | |
return reject(err) | |
else if (item.done) | |
return resolve(context) | |
else | |
item.value(context, getHandler(handlers.next())) | |
} | |
} | |
const next = getHandler(handlers.next()) | |
next() | |
}) | |
} | |
getChain() { | |
return this.chain.slice() | |
} | |
} | |
Chain.Chain = Chain | |
exports = module.exports = Chain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment