this value inside anonymous generator

# Niloy Mondal (10 years ago)

I wrote some code like the following in tracuer

class Foo {
  constructor() {
    spawn(function*() {
      let data = yield this.fetchData(); // error because 'this' is
undefined
    });
  }

  fetchData() {
    // returns promise
  }
}

I used the spawn function from here: gist.github.com/jakearchibald/31b89cba627924972ad6

The code doesn't work because 'this' is undefined. I can fix it by using 'let that = this' pattern. But it feels like a step backward now that I've fallen in love with lambda functions. So I was wondering if it would be possible to use lexical binding for 'this' inside anonymous generators.

# Jordan Harband (10 years ago)

Can you not just use .bind here?

spawn(function* () {
  let data = yield this.fetchData();
}.bind(this));
# Leon Arnott (10 years ago)

Some old TC39 notes talk about the possibility of generator arrows, and discarded them in ES6 for what was basically a syntactic quandry. (I personally prefer =*>

because I like the arrow resembling a flowchart-like connector, with the shaft and point connecting the params and body, and the * being a little label in the middle. But, those are just aesthetics.)

# Kevin Smith (10 years ago)

Generator arrows are a possibility, but we need to see how the use cases develop in practice. For the specific use case in the OP, async arrows would actually be a better fit.