TypeScript - How can I access "this" in async method -
i have 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 can see line console.log(this.resource)
, undefined. can't async methods access "this"?
i tested console.log(this)
, , returns profile { }
in web inspector.
is there way can access this
?
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 sample script 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 output
1
as expected. conclusion it's not this
keyword. it's resource
class, guess.
Comments
Post a Comment