导入的异步函数的 Async Await 未正确等待

时间:2021-05-18 22:29:53

标签: javascript node.js reactjs asynchronous

我很困惑。

我创建了一个异步实用程序函数,我正在将其从一个文件导出并导入到 React 类组件中。该函数对返回一个对象的身份验证服务进行 API 调用。

我的目标是能够在我的组件中调用该函数,并将返回的对象设置为一个名为“tokens”的变量,然后我可以进一步操作该变量。

我的问题是,无论我似乎如何格式化,我都无法让组件中的函数在继续之前等待异步函数的返回。

这是效用函数的简化版本:

// configure and send API request using Axios library
export const retrieveTokens = async () => {
  
  // configure request
  var config = {
    // configs
  };

  // send request
  axios(config)
    // handle response
    .then(function (response) {
      let cognitoTokens = response.data;
      console.log("A:")
      console.log(cognitoTokens);
      return cognitoTokens;
    })
    // handle error
    .catch(function (error) {
      console.log(error);
    });
};

然后这个实用函数被导入到 React 类组件中,如下所示:

import React, { Component } from "react";
import { retrieveTokens } from "./utils.js";

class HeaderLogic extends Component {
  componentDidMount() {
    async function authenticationFlow() {
      let tokens = await retrieveTokens();
      console.log("B:");
      console.log(tokens);

    }
    authenticationFlow();
  }

  render() {
    return <></>;
  }
}

export default HeaderLogic;

我的预期结果是:

A:
{Tokens}

B:
{Tokens}

但我只能得到

B:
Undefined

A:
{Tokens}

我尝试了各种不同的语法,但我根本无法让 authenticationFlow() 中的控制台日志等待!

1 个答案:

答案 0 :(得分:2)

你忘了return。另外,如果函数内部没有任何 async,请不要将函数声明为 await(不是说它会导致任何问题,而是无用):

// configure and send API request using Axios library
export const retrieveTokens = () => {
  
  // configure request
  var config = {
    // configs
  };

  // send request
  return axios(config)
    // handle response
    .then(function (response) {
      let cognitoTokens = response.data;
      console.log("A:")
      console.log(cognitoTokens);
      return cognitoTokens;
    })
    // handle error
    .catch(function (error) {
      console.log(error);
    });
};
相关问题