0

im trying to use a async.queue in a class so i am able to use class variables. However if im trying to do so the variables are not defined. Is there any way to use it how expected?

class TestClass {
    constructor() {
        this.a = 'Hello World'
        this.q = async.queue(this.hello, 1)
    }

    hello(item, callback) {
        console.log(item)
        console.log(this.a) /* Not defined */
        callback()
    }

    start() {
        my_jobs = ['Foo', 'Bar',]
        my_jobs.forEach(element => {
            this.q.push(element)
        })
    }
}

my_class = new TestClass()
my_class.start()

1 Answer 1

1
var async = require('async');

class TestClass {
    constructor() {
        this.a = 'Hello World';
        this.q = async.queue(this.hello.bind(this), 1); /* use .bind to keep context*/
    }

    hello(item, callback) {
        console.log(item);
        console.log(this.a); /* Defined: Hello World */
        callback();
    }

    start() {
        var my_jobs = ['Foo', 'Bar'];

        my_jobs.forEach(element => {
            this.q.push(element);
        });
    }
}

my_class = new TestClass();
my_class.start();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.