Felix Lebel February 2016

TypeScript - How can I access "this" in async method

I have this piece of code:

export class Profile {

    private resource: Resource = new Resource();


    /**
     * Problem here
     */
    async initialize(): Promise<void> {
        console.log(this.resource);

        var html = await this.resource.fetch(true);

        const $profile = jQuery(html);

        console.log($profile.find("span.largetext"));


    }
}

If you can see the line console.log(this.resource), I get undefined. Can't async methods access the "this"?

I also tested with console.log(this), and it returns Profile { } in the web inspector.

Is there a way I can access this?

Answers


Martin Vseticka February 2016

class Profile {

    private resource: number = 1;


    /**
     * Problem here
     */
    async initialize(): Promise<void> {
        console.log(this.resource);
    }
}


let p = new Profile();
p.initialize();


let p = new Profile();
p.initialize();

I created this sample script which transpiles to

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
    return new Promise(function (resolve, reject) {
        generator = generator.call(thisArg, _arguments);
        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
        function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
        function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
        function step(verb, value) {
            var result = generator[verb](value);
            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
        }
        step("next", void 0);
    });
};
class Profile {
    constructor() {
        this.resource = 1;
    }
    /**
     * Problem here
     */
    initialize() {
        return __awaiter(this, void 0, Promise, function* () {
            console.log(this.resource);
        });
    }
}
let p = new Profile();
p.initialize();
//# sourceMappingURL=main.js.map

and the output is

1

as expected. So the conclusion is that it's not about this keyword. It's about Resource class, I guess.

Post Status

Asked in February 2016
Viewed 2,050 times
Voted 14
Answered 1 times

Search




Leave an answer