【发布时间】: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