2016-09-09 6 views
0

내 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을 사용할 수 있다는 가정하에있었습니다.

+1

'bind'로 해결하려는 실제 문제에 대해서는 훨씬 더 좋은 해결책이 있음을 주목하십시오 (http://stackoverflow.com/q/28250680/1048572). – Bergi

답변

1

아니오; 그것은 화살표 기능이하는 것과 정확히 반대입니다.

화살표 함수는 그들의 용기 블럭의 this을 상속 엄격 어휘 this – 사용합니다.

bind()과 상관없이 또는 화살표 기능을 호출 할 때 수동으로 this으로 전달하면 해당 this은 항상 포함 된 범위에서 가져옵니다.