簡體   English   中英

導入異步 function 的 Async Await 未正確等待

[英]Async Await of imported asynchronous function not waiting correctly

我很困惑。

I have created an asynchronous utility function that I am exporting from one file and importing into a React Class Component.The function makes an API call to an authentication service which returns an object.

我的目標是能夠在我的組件中調用 function 並將返回的 object 設置為一個名為“令牌”的變量,然后我可以進一步操作該變量。

我的問題是,無論我如何格式化它,我都無法在組件中獲取 function 以等待異步 function 返回,然后再繼續。

這是實用程序 function 的簡化版本:

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

然后這個實用程序 function 被導入到 React Class 組件中,如下所示:

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()等待!

你忘了return 另外,如果 function 內部沒有任何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);
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM