首页 > 解决方案 > 从异步方法分配变量

问题描述

我使用 AWS-Amplify 并希望从 Cognito 获取所有者并将其分配给变量所有者。当我在console.log(user.username)里面做时,then(我看到了正确的数据。但是,当我这样做时,console.log(owner);我只看到空值。

function App() {
  // Get user
  let owner = null;

  Auth.currentAuthenticatedUser({
    bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
  })
    .then(user => {
      owner = user.username;
    })
    .catch(err => console.log(err));

  console.log(owner);

标签: reactjsaws-amplify

解决方案


function App() {
  // Get user
  let owner = null;

  return Auth.currentAuthenticatedUser({
    bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
  })
    .then(user => {
      owner = user.username;
      console.log(owner);
      return owner
    })
    .catch(err => console.log(err));

由于 Auth 是异步的,因此 console.log(owner) 在 promise 解决之前执行。将其移至 then 以查看结果。


推荐阅读