Skip to content

Fat arrow doesn't work for async methods #4349

Closed

Description

@al6x

The binding for fat arrow is lost if you wrap class method with some function. I demonstrate it with async example, but it's not tied to it, the behaviour will be the same for any other function too.

class Events
  handle: async (event) =>
    console.log @

Will produce (note the this is lost, actually it's not even lost but completely wrong, the Events is used instead of this):

var Events;

Events = (function() {
  function Events() {}

  Events.prototype.handle = async(function(event) {
    return console.log(Events);
  });

  return Events;
})();

It should produce:

var Events,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

Events = (function() {
  function Events() {
    this.handle = bind(this.handle, this);
  }

  Events.prototype.handle = async(function(event) {
    return console.log(this);
  });

  return Events;

})();

Activity

  1. changed the title [-]Wrong class code-generation for async methods[/-] [+]Fat arrow method doesn't work for async methods[/+] on Oct 30, 2016
  2. changed the title [-]Fat arrow method doesn't work for async methods[/-] [+]Fat arrow doesn't work for async methods[/+] on Oct 30, 2016
  3. thinkingofmaud commented on Oct 31, 2016

    @thinkingofmaud

    That's intended. The fat arrow syntax expresses a function that inherits the context from the outer expression.

    Inside a class declaration, the context is the class itself.

    I think the syntax for

    class Events
      handle: =>
        #inside the method, 'this' is not the outer context (Events) but the Events instance.
        console.log this
    

    is wrong, but that should break some old code.

    assuming async is a decorator function, you may write your code as

    class Events
      handle: -> do async (event) =>
        console.log @
    

    so the fat arrow expression is written inside the instance context, that I assume is the one you want to pass along.

  4. GeoffreyBooth commented on Oct 31, 2016

    @GeoffreyBooth
    Collaborator

    The title of your issue is confusing. This isn’t really an “async method”, it just happens to be that you’re passing a method as an argument to a function named async.

    We’re working on true async support in #3757.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions