0

I'm dealing with a project that uses AWS Cognito. There are some configuration params that needs to be fetched from server with an API call. I keep the API call in a config.js file and use async/await to get response from server like this

const getCognitoConfigs = async () => {
const res = await axios.get(`${apiurl.apiurl}/logininfo`);
console.log(res.data);
return res.data;
}; 

export default getCognitoConfigs;

And in my index.js (where I set up Cognito), I import the function from config.js file

import getCognitoConfigs from "./config";
const configs = getCognitoConfigs();

Amplify.configure({
    Auth: {
        mandatorySignIn: true,
        region: configs.cognito.region,
        userPoolId: configs.cognito.user_pool,
        userPoolWebClientId: configs.cognito.app_client_id
    }
});

The problem is async await does not stop the program execution so I'm getting 'configs' as undefined. Are there anyways that I can make the app stop until the api call has resolved? Thanks.

4
  • Can you await getCognitoConfigs() in index.js by wrapping it in an (anonymous) async function? Otherwise you could retrieve the results of the getCognitoConfigs() promise using .then(); Commented Dec 10, 2019 at 14:45
  • I've tried doing this and still gets an error ('configs' as null) let configs = null; (async function() { const res = await getCognitoConfigs(); console.log(res); configs = res; })(); Commented Dec 10, 2019 at 14:51
  • Are you running Amplify.configure in the same anonymous async function? If you don't, configs will simply be null as the async function only gets executed after you run Amplify.configure. Commented Dec 10, 2019 at 14:56
  • ah yes, I put the Amplify stuff out of the anonymous function. Changed that and it worked. Thanks. Commented Dec 10, 2019 at 14:57

1 Answer 1

0

If you want to use async/await, you have to wrap index.js in an asynchronous function and add

await getCognitoConfigs();

or you can use promise like

getCognitoConfigs().then(res => Amplify.configure({...}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.