Atmocreations
Atmocreations

Reputation: 10061

Keep the scope in Async.js

Given the following class in Coffeescript:

class MyClass extends events.EventEmitter

    someObj: null # set somewhere during constructor

    someMethod: () ->
        async.parallel([
            @task1,
            @task2,
            @task3,
        ], (err, results) ->
            doSomething()

    task1: (callback) ->
            @someObj.funnyMethod()   # fails
            callback()
);

The call for @someObj.funnyMethod() on the second last line fails:

TypeError: Cannot read property 'funnyMethod' of undefined

Obviously, this refers to the context inside the callback. For normal callbacks, I've learned we would use the fat arrow operator => instead of the thin one ->.

What's a clean way to handle this with async.js (or any other similar library)?

Upvotes: 1

Views: 364

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

You can use the fat arrow in the definition of task1:

task1: (callback) =>

However, I wouldn't recommend it. A fat arrow for methods is quite different from a fat arrow for functions, and has performance penalties.

What you probably want is to pass bound versions of those functions to async.parallel. You can either do this with Function::bind, or with anonymous fat-arrow functions:

@task1.bind(@), # Function::bind
=> @task2(),    # anonymous function

Upvotes: 1

Related Questions