NickC
NickC

Reputation: 377

Async Await of imported asynchronous function not waiting correctly

I'm flummoxed.

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.

My goal is to be able to call that function in my component and set the returned object equal to a variable called "tokens" which I can then further manipulate.

My problem is that no matter how I seem to format this i'm unable to get the function in the component to wait for the return of the async function before moving on.

Here is a simplified version of the utility 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);
    });
};

and then this utility function is being imported into the React Class Component like so:

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;

My expected result would be:

A:
{Tokens}

B:
{Tokens}

but I am only able to get

B:
Undefined

A:
{Tokens}

I have tried various different syntax's and I simply cannot get the console logs in authenticationFlow() to await!

Upvotes: 1

Views: 951

Answers (1)

Guerric P
Guerric P

Reputation: 31815

You forgot to return. Also, don't declare a function as async if you don't have any await inside it (not that it causes any problem but it's just useless):

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

Upvotes: 2

Related Questions