0

I'm having issues getting ES6 Arrow functions working properly with my Bookshelf/Bluebird promise chain.

This is the working code when using ES5 and Bluebird's .bind({}):

exports.prospectorLead = function (query) {
    return new Lead().where('id', query.lead_id).fetch({withRelated: Lead.RELATED, require: true })
    .bind({})
    .then(function (lead) {

        this.lead = lead.serialize();
        this.company = this.lead.company.serialize();

        return API('prospector', 'v1/people/search', {
          query: query.domain,
        });
    })
    .then(function (prospects) {
       console.log(this.lead.id, this.company.domain, prospects);
    })
}

This is the broken code when using ES6 Arrow functions that do not have this set properly:

exports.prospectorLead = function (query) {
  return new Lead().where('id', query.lead_id).fetch({withRelated: Lead.RELATED, require: true })
  .then((lead) => {

    this.lead = lead.serialize();
    this.company = this.lead.company.serialize();

    return API('prospector', 'v1/people/search', {
      query: query.domain
    });
  })
  .then((prospects) => {
    console.log(this.lead.id, this.company.domain, prospects);
  })
}

The problem I'm seeing is that the scope of this is set not to the exports.propspectorLead() function, but instead to the scope of the whole module. Which was not an issue when calling the function one off, but when I make a ton of async calls to this function, my data becomes corrupt because this is not scoped properly.

What am I missing here? I was under the assumption that using the arrow functions would allow me to use this throughout my promise chain.

simon-p-r
  • 3,623
  • 2
  • 20
  • 35
  • 1
    Notice that for the actual problem which you're trying to solve with `bind` there are [much better solutions](http://stackoverflow.com/q/28250680/1048572). – Bergi Sep 09 '16 at 01:42

1 Answers1

1

No; that's exactly the opposite of what arrow functions do.

Arrow functions use strictly lexical this – they inherit the this of their containing block.

No matter what you bind() or manually pass as this when calling the arrow function, its this will always come from the containing scope.

zerkms
  • 249,484
  • 69
  • 436
  • 539
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964