TypeScript - 如何在异步方法中访问 "this"

标签 typescript async-await ecmascript-6

我有这段代码:

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"));


    }
}

如果你能看到 console.log(this.resource) 这行,我得到了未定义。异步方法不能访问“this”吗?

我还使用 console.log(this) 进行了测试,它在网络检查器中返回了 Profile { }

有什么方法可以访问 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();

我创建了这个转换为的示例脚本

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

输出是

1

如预期。所以结论是,它与 this 关键字无关。我猜是关于 Resource 类。

关于TypeScript - 如何在异步方法中访问 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35264469/

相关文章:

javascript - typescript 中的 useContext 和 useReducer

typescript - ASP.NET 核心项目 : How to keep Typescript from Compiling

typescript - 在整个 WebStorm 项目中将缩进从 2 个空格更改为 4 个空格

javascript - async/await 不会将构建的数组返回到父 array.map()

javascript - React 检测到 Navigation 调用的 Hooks 的顺序发生了变化

javascript - Promise 返回空值,尽管它存在于数据库中

javascript - useState 与异步函数返回 Promise {<pending>}

javascript - React Native如何在JSX中循环View组件

javascript - 如何在 JavaScript 中使用解构——在将传递给 React 组件的辅助函数中?

javascript - 迁移到react-router v4 - 需要 router props 的子路由