reactjs - 从异步方法分配变量
问题描述
我使用 AWS-Amplify 并希望从 Cognito 获取所有者并将其分配给变量所有者。当我在console.log(user.username)
里面做时,then(
我看到了正确的数据。但是,当我这样做时,console.log(owner);
我只看到空值。
function App() {
// Get user
let owner = null;
Auth.currentAuthenticatedUser({
bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
})
.then(user => {
owner = user.username;
})
.catch(err => console.log(err));
console.log(owner);
解决方案
function App() {
// Get user
let owner = null;
return Auth.currentAuthenticatedUser({
bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
})
.then(user => {
owner = user.username;
console.log(owner);
return owner
})
.catch(err => console.log(err));
由于 Auth 是异步的,因此 console.log(owner) 在 promise 解决之前执行。将其移至 then 以查看结果。
推荐阅读
- dockerfile - Docker从dockerfile图像错误运行容器
- android - 使用带有选项卡布局片段的自定义布局更改适配器中的文本颜色
- c++ - Visual Studio 远程调试 Makefile 项目的远程输出路径错误
- python - 如何在python中遍历两个数据框
- java - 如何使用 Firebase Firestore 获取查询数据?
- datatables - 数据表和 YADCF - 多选过滤器
- python - 如何在 python 中运行 netstat -nb
- angular - 如何使用带有 Angular 5 和 Material Design 的 innerHtml 更新动态文本
- javascript - 连接到花式树的可排序在拖放时忘记了它的位置
- python - 自定义函数来获取数据框值的位置