简体   繁体   English

从异步函数导入数据

[英]Import data from async function

I'm dealing with a project that uses AWS Cognito.我正在处理一个使用 AWS Cognito 的项目。 There are some configuration params that needs to be fetched from server with an API call.有一些配置参数需要通过 API 调用从服务器获取。 I keep the API call in a config.js file and use async/await to get response from server like this我将 API 调用保留在 config.js 文件中,并使用 async/await 从服务器获取响应,如下所示

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在我的 index.js(我设置 Cognito 的地方)中,我从 config.js 文件导入函数

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.问题是 async await 不会停止程序执行,所以我得到的 'configs' 未定义。 Are there anyways that I can make the app stop until the api call has resolved?无论如何,我可以让应用程序停止,直到 api 调用解决吗? Thanks.谢谢。

If you want to use async/await, you have to wrap index.js in an asynchronous function and add如果你想使用 async/await,你必须将 index.js 包裹在一个异步函数中并添加

await getCognitoConfigs();

or you can use promise like或者你可以像这样使用承诺

getCognitoConfigs().then(res => Amplify.configure({...}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM