Using/Binding 'this' ES6 中的 Bookshelf Promises
Using/Binding 'this' with Bookshelf Promises in ES6
我在使 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
。
否;这与箭头函数的作用正好相反。
箭头函数严格使用词法 this
——它们继承了包含块的this
。
无论您在调用箭头函数时 bind()
还是手动传递 this
,它的 this
将始终来自包含范围。
我在使 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
。
否;这与箭头函数的作用正好相反。
箭头函数严格使用词法 this
——它们继承了包含块的this
。
无论您在调用箭头函数时 bind()
还是手动传递 this
,它的 this
将始终来自包含范围。