내 Bookshelf/Bluebird 약속 체인에서 제대로 작동하는 ES6 Arrow 기능을 얻는 데 문제가 있습니다. ES5와 블루 버드의 .bind({})
를 사용하는 경우 'this'with ES6의 Bookshelf 약속 사용/바인딩
이
는 작업 코드 :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'로 해결하려는 실제 문제에 대해서는 훨씬 더 좋은 해결책이 있음을 주목하십시오 (http://stackoverflow.com/q/28250680/1048572). – Bergi