yapc
v1.4.2
Published
Yet Another Promise Chainer
Downloads
30
Readme
Yet Another Promise Chainer
- Native promise-based method chaining
- ES6 Class-based, easily extensible
- Built for
async/await
- Zero dependencies
Usage
const fs = require('fs')
const { Chainable } = require('./index')
class MyChainableClass extends Chainable {
// Chain any method that returns a promise
loadFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, file) => {
if (err) throw err
this.file = file
resolve(this.file)
})
})
}
// Execute non-promise functions in the order chained
transformFile(handler) {
if (!this.file) throw new Error('File not loaded!')
this.fileTransformed = handler(this.file)
return this.fileTransformed
}
// Returns output at the end of the chain
outputResults() {
const output = (this.fileTransformed || this.file).toString()
process.stdout.write(output)
return output
}
}
;(async () => {
const chain = new MyChainableClass()
// Build the chain of operations
chain
.loadFile('./package.json')
.transformFile((file) => new Buffer.from(
file.toString().replace('yapc', 'sucky-package')
))
.outputResults()
// Execute, sequentially, in the order called
console.log('modified package.json:', await chain)
})()