ES6 and variable scope inside a promise

荒凉一梦 提交于 2019-12-01 20:42:14

You need to do two things. First, use an arrow function, and second, use `this.contact = data;

activate(id) {
  this.id = id;
  return dpd.contacts.get(id).then(data => {
    console.log(data);
    this.contact = data;
  });
}

You use an arrow function because it deals with JavaScript's "this" issue, where this refers to the lexical scope of the function, and not the object you're currently in. Using an arrow function makes sure that this outside the arrow function is the same as this inside the arrow function.

You need to use this.contact because contact is an instance property of the class.

The problem is that contact = data; will update the value of the local contact variable, but will not change the value of the this.contact. You need to update the contact contact property instead. The problem is that you do not have access to this inside the core of your function.

There is different ways to solve this.

1- You can save activate's context (this) into a variable in the closure of activate so that you can access it inside the core of then.

activate(id) {
    this.id = id;
    let that = this;
    return dpd.contacts.get(id).then(function(data) {
      console.log(data);
      that.contact = data;
    });
  }

2- You can bind the function to this so you can access it.

activate(id) {
    this.id = id;
    return dpd.contacts.get(id).then(function(data) {
      console.log(data);
      this.contact = data;
    }.bind(this));
  }

3- (recommended with ES6) you can use an arrow function (arrow functions preserve the context)

activate(id) {
    this.id = id;
    return dpd.contacts.get(id).then((data) => {
      console.log(data);
      this.contact = data;
    });
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!