cyberwombat
cyberwombat

Reputation: 40084

Bind issues with Bluebird promises

I am having some difficulties with promises and bind.

I have 2 clases:

// A Model/DB connnection of sorts
function Connection() {

}
Connection.prototype.findOrder = function(id) {
  // Returns promise
}


// The main class 
function Main(connector) {
  this.connector = connector;
}

Main.prototype.buildInvoice = function(report) {
  return P.map(ids, self.connector.findOrder.bind(self, id);
  // Yields: Cannot read property 'bind' of undefined
};

Called like this:

var connection = new Connection({
  connection: config.db.mongo.connection
});

var main = new Main({ connection: connection });

P.each(reports, main.buildInvoice.bind(main));

I am running into bind issues. I was first getting this error for the line above:

Unhandled rejection TypeError: undefined is not a function

I subsequently added the bind found on P.each(reports, main.buildInvoice.bind(main));. However the same issue came up for the buildInvoice method but I have not managed to figure out the syntax. The code as posted yields Cannot read property 'bind' of undefined

What is the correct syntax to make this call:

Main.prototype.buildInvoice = function(report) {
  var self = this;
  return P.map(ids, self.connector.findOrder.bind(self, id);
};

This is probably a non promise related issue but i am posting as this as I am at the same time wondering if I am handling this flow correctly.

Upvotes: 0

Views: 150

Answers (1)

Bergi
Bergi

Reputation: 664346

For one thing, your call new Main({ connection: connection }); doesn't match your constructor function:

function Main(connector) {
  this.connector = connector;
}

which expects the connection to be passed by itself, not wrapped in an object. Therefore, when setting .connector to that object you pass in, its .findOrder will be undefined. Use

var main = new Main(connection);

Second, you will need to bind the findOrder method to the connection object, not to self. Oh, and self is called this in JS. And there's no id that you want to partially apply. So use

Main.prototype.buildInvoice = function(report) {
  return P.map(ids, this.connector.findOrder.bind(this.connector));
};

Upvotes: 1

Related Questions