【问题标题】:Async Await of imported asynchronous function not waiting correctly导入的异步函数的 Async Await 未正确等待
【发布时间】:2021-08-08 04:38:51
【问题描述】:

我很困惑。

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

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

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

以下是实用函数的简化版本:

// 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() 中的控制台日志等待!

【问题讨论】:

  • 需要添加promise才能retrieveTokens
  • flummoxed 这个词很有趣,谢谢你教我这个

标签: javascript node.js reactjs asynchronous


【解决方案1】:

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

// 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);
    });
};

【讨论】:

  • 就是这样。非常感谢。
  • 很高兴它有帮助!
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 2020-05-15
  • 2019-07-17
  • 2020-12-23
  • 1970-01-01
  • 2019-08-28
  • 2018-09-23
  • 2018-05-27
相关资源
最近更新 更多