somehow to pass context
tunnckoCore opened this issue · comments
To the each function? Actually it would be same for all in stack.
function fn1 (cb) {
assert.equal(this.hello, 'world')
this.foo = 'foo'
cb(null, 1)
}
function fn2 (cb) {
assert.equal(this.foo, 'foo')
assert.equal(this.hello, 'world')
this.bar = 'bar'
cb(null, 2)
}
function fn3 (cb) {
assert.equal(this.bar, 'bar')
assert.equal(this.hello, 'world')
cb(null, 3)
}
var seriesDone = bach.series(fn1, fn2, fn3)
seriesDone({hello: 'world'}, function (err, res) {
console.log(res)
//=> [1, 2, 3]
})
like middleware/plugin stack
bach
is all about function composition. The above can be achieved like
function fn1 (cb) {
assert.equal(this.hello, 'world')
this.foo = 'foo'
cb(null, 1)
}
function fn2 (cb) {
assert.equal(this.foo, 'foo')
assert.equal(this.hello, 'world')
this.bar = 'bar'
cb(null, 2)
}
function fn3 (cb) {
assert.equal(this.bar, 'bar')
assert.equal(this.hello, 'world')
cb(null, 3)
}
var ctx = {hello: 'world'};
var seriesDone = bach.series(fn1.bind(ctx), fn2.bind(ctx), fn3.bind(ctx))
series(function (err, res) {
console.log(res)
//=> [1, 2, 3]
})
It is a little more verbose, but being verbose and explicit never hurt anyone. It also allows you to avoid passing context to some functions if you want.