【发布时间】:2016-09-09 01:00:43
【问题描述】:
我在使 ES6 Arrow 函数与我的 Bookshelf/Bluebird 承诺链正常工作时遇到问题。
这是使用 ES5 和 Bluebird 的 .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 的 ES6 箭头函数时出现的错误代码:
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);
})
}
我看到的问题是this 的范围不是设置为exports.propspectorLead() 函数,而是设置为整个模块的范围。一次性调用函数时这不是问题,但是当我对该函数进行大量异步调用时,我的数据会损坏,因为this 的范围不正确。
我在这里缺少什么?我假设使用箭头函数可以让我在整个承诺链中使用this。
【问题讨论】:
-
请注意,对于您尝试使用
bind解决的实际问题,有much better solutions。
标签: node.js ecmascript-6 es6-promise hapijs bookshelf.js