【问题标题】:Using/Binding 'this' with Bookshelf Promises in ES6 [duplicate]在 ES6 中使用/绑定“this”和 Bookshelf Promises [重复]
【发布时间】: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

【问题讨论】:

标签: node.js ecmascript-6 es6-promise hapijs bookshelf.js


【解决方案1】:

没有;这与箭头函数的作用完全相反。

箭头函数使用严格的词法 this——它们继承了包含块的this

无论你在调用箭头函数时bind() 或手动传递为this,其this 将始终来自包含范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2016-06-07
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多