javascript - 在 promise 中使用这个

标签 javascript react-native promise

我想在第二个 then 方法中从 fetch 中访问 this

但它一直说:TypeError: _this2.login is not a function

  fbAuth() {
    LoginManager.logInWithReadPermissions(['public_profile']).then(function(res) {
      if (res.isCancelled) {
        console.info('cancelled');
      } else {
        console.info('login success');

        AccessToken.getCurrentAccessToken().then((data) => {
          let req = new GraphRequest('/me', {
            httpMethod: 'GET',
            version: 'v2.5',
            parameters: {
              'fields': {
                'string' : 'id,email,name'
              }
            }
          }, (err, res) => {
            const data = new FormData();
            data.append('facebook_user_id', res.id);
            data.append('email', res.email);
            data.append('name', res.name);

            fetch('xxxxxxxxxxx', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              body: data,
            })
              .then((response) => response.json())
              .then((responseJson) => {
                this.login(responseJson);
              })
              .catch((error) => {
                console.error(error);

                alert('Something went wrong. Please try again, if the problem persists contact the @lacarte service desk');
              });
          });

          new GraphRequestManager().addRequest(req).start();
        });
      }
    }, function(error) {
      console.error(error);
    });
  }

最佳答案

假设 this 应该与也具有 fbAuth 方法的 this 相同,您应该为第一个 Promise 使用箭头函数声明还有:

LoginManager.logInWithReadPermissions(['public_profile']).then(res => {
...
});

关于javascript - 在 promise 中使用这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501779/

相关文章:

javascript - 是否可以返回 0 的小数点后两位的浮点值?

javascript - SetState 回调不等待状态更新

android - 使用动态页面 View 对 native ViewPagerAndroid 使用react

reactjs - 在 ReactJS 中卸载组件时取消 promise

javascript - 如何更改 HTML 鼠标输入的背景颜色

javascript - 如何将 Vuejs 中的仪表板模板集成到 Laravel 5.7 项目中

javascript - 那么如何进行异步呢?

Angular 8 : Using HttpClient. get.toPromise

javascript - 如何删除 jQuery 中特定表格行下方的所有表格行

react-native - 在React Native中如何重用功能?