如何将回调函数包装在其他回调函数中并从中调用

How to wrap callback function in other callback function and call from there?

本文关键字:函数 回调 调用 其他 包装      更新时间:2023-10-20

以下是我的代码:

        var me = this;
        gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) {
            if (authResult && !authResult.error) {
                me.accessToken = authResult.access_token;
            } else {
              //TODO : show error in front end
            }
        });

当我使用这样的回调函数时。

gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, AuthResult);
function AuthResult(authResult: any) {
                if (authResult && !authResult.error) {
                    me.accessToken = authResult.access_token;
                } else {
                  //TODO : show error in front end
                }

我没有得到回调函数中的me属性

我如何将回调函数包装在其他回调函数中,在那里我也可以在JS 中获得作用域

使用胖箭头:

    gapi.auth.authorize({ client_id: client, scope: scope, immediate: true },AuthResult);
    const AuthResult = (authResult: any) => {
            if (authResult && !authResult.error) {
                this.accessToken = authResult.access_token;
            } else {
              //TODO : show error in front end
            }

更多

不使用.bind:https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html至少还没有

使用.bind:

gapi.auth.authorize(..., AuthResult.bind(this));
function AuthResult(...) {
  // use `this` instead of `me`
}

另请参阅如何在回调中访问正确的"this"上下文?