Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

somehow to pass context #13

Closed
tunnckoCore opened this issue Jun 22, 2015 · 1 comment
Closed

somehow to pass context #13

tunnckoCore opened this issue Jun 22, 2015 · 1 comment

Comments

@tunnckoCore
Copy link

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

@phated
Copy link
Member

phated commented Jun 23, 2015

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.

@phated phated closed this as completed Jun 23, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants