Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 and variable scope inside a promise

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 seems dirty to have to do that.

export class contactEdit {
  static t; // static class var
  constructor() {
    this.id = null;
    this.contact = null;
    contactEdit.t = this;
  }

  activate(id) {
    this.id = id;
    let contact = this.contact; // scoped version of class var
    return dpd.contacts.get(id).then(function(data) {
      console.log(data);
      contactEdit.t.contact = data; // this works
      contact = data; // this doesn't
    });
  }
}

Normally I would create a var contact inside the activate() function (it works in the Chrome console) but this doesn't seem to working in ES6.

Chrome console:

var c = null;
undefined
c;
null
dpd.contacts.get('a415fdc8f5a7184d').then(function(data) {
      c = data;
    });
Object {}fail: (n)then: (e,t)__proto__: Object
c;
Object {firstName: "John", lastName: "Doe", id: "a415fdc8f5a7184d"}
like image 702
Andrew Grothe Avatar asked Jul 26 '16 15:07

Andrew Grothe


People also ask

How do you access the variable this inside then scope?

var a = this; one(). then(function () { console. log(a) }); Update: use an arrow function - they borrow the context ( this ) from their outer scope.

What is nested scope in JavaScript?

Scopes can be nested. Inside an inner scope you can access the variables of an outer scope. The lexical scope consists of the outer function scopes determined statically. Any function, no matter the place where being executed, can access the variables of its lexical scope (this is the concept of closure).

What are the three types of scopes in JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.

What is scope in es6?

The block scope restricts a variable's access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block.


1 Answers

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.

like image 94
Ashley Grant Avatar answered Jan 03 '23 16:01

Ashley Grant