ES6 and variable scope inside a promise

后端 未结 2 1179
执笔经年
执笔经年 2021-01-19 01:04

Not sure what I\'m missing here.

I need to get the output of data into this.contact. Right now, I\'m using a static class variable, but it

2条回答
  •  一向
    一向 (楼主)
    2021-01-19 01:26

    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 body of your anonymous function (or rather, the this of the anonymous function is not going to be the same this as activate's).

    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 activate's this so that it is called with the same context.

    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 do not have their own context, so they preserve the one where they are created)

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

提交回复
热议问题