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.