2
\$\begingroup\$

I've seen tutorials about node promises and such but not using bind. I feel like I can do lots of things this way and keep everything clean:

Updater.prototype.generateLocFieldForDocs = function(docs) {
  console.log('list obtained')
  async.eachLimit(docs, 10, this.generateLocFieldForDoc.bind(this), this.generateLocFieldForDocsDone.bind(this))
}

Updater.prototype.generateLocFieldForDoc = function(doc, done) {
  this.collection.update({_id: doc._id},
  {$set: {
    loc: {...}
  }}, function(err, result) {
    this.errorHandler(err)
    done()
  }.bind(this))
}

Updater.prototype.generateLocFieldForDocsDone = function(err) {
  this.errorHandler(err)
  this.generateLocFieldNextSection()
}

What do you think about using classes and bind like this in node.js?

What bind does is that it's sets the this in the function body to the this passed to bind therefore keeping the context you want.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Not sure I understand the question: Asynchronous operations and context binding are orthogonal concepts. Asynchronous callbacks just happen to be a good use case for bind, but there are other ways of ensuring the correct context. I mean, the code looks fine; it's one solution among many. If you like it and it works, go with it. \$\endgroup\$
    – Flambino
    Sep 2, 2015 at 10:57

1 Answer 1

1
\$\begingroup\$

I've realized there's no need for all these prototype functions and binds. When using node.js, in a file, the normal named functions are private to the file, so it can be used as methods.

var self = {
  parallelLimit: 10
}

function generateLocFieldForDocs(docs) {
  log('list obtained')
  async.eachLimit(docs, self.parallelLimit, generateLocFieldForDoc, generateLocFieldForDocsDone)
}

function generateLocFieldForDoc(doc, done) {
  self.collection.update({_id: doc._id},
  {$set: {
    loc: {...}
  }}, function(err, result) {
    errorHandler(err)
    done()
  })
}

function generateLocFieldForDocsDone(err) {
  errorHandler(err)
  generateLocFieldNextSection()
}

Using module.export.myFunction = makes it public

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.