javascript - 使用 oath 时 Amplify.Hub 登录处理程序中的竞争条件
问题描述
示例代码:
Hub.listen('auth', event => {
const { event: type, data } = event.payload;
if (type === 'signIn') {
const session = data.signInUserSession;
console.log('SESSION', data.signInUserSession);
setTimeout(() => {
console.log('SESSION', data.signInUserSession);
}, 100);
}
});
使用 oath 时,提供程序重定向到我的应用程序后,集线器会触发一个signIn
事件。但是,该signInUserSession
属性是null
触发事件的时间,但会在一段时间后(100 毫秒内)获得一个值。直接使用时似乎不会出现这种情况Auth.signIn(email, password)
;signInUserSession
触发事件时填充。
这里发生了什么,我该如何解决?目前,我在代码中有一个明确的延迟,这是一个可怕的黑客攻击。
解决方案
也许 JavaScript 等待填充值的旧方法有助于确保代码不会失败,即使填充值的时间比预期的要长。
这是我通常在没有其他选项可用时使用的示例代码。
waitForValue(){
if(myVar!= null && typeof myVar !== "undefined"){
//value exists, do what you want
console.log(myVar)
}
else{
setTimeout(() => {this.waitForValue()}, 100);
}
}
您可以根据需要重构此示例代码。
或者,AWS Amplify 也有其他方法来获取当前登录的用户会话。例如Auth.currentAuthenticatedUser()
并Auth.currentSession()
返回承诺。它们可以像这样使用
private async getUser(){
let user = null;
try {
user = await Auth.currentAuthenticatedUser();
//console.log(user);
} catch (err) {
//console.log(err);
}
//return user;
}
推荐阅读
- python-3.x - Python添加列条件未按预期工作
- zooming - 添加缩放时轴标签消失(Vega-Lite)
- cryptocurrency - openSea NFT SDK,如何使用 api 买卖 NFT
- excel - 减去成对单元格的公式 - excel
- arrays - 我如何只能从 json 响应中按类别显示对象?
- java - Webview 活动在失去焦点时调用 onDestroy()
- python - 在文件读取期间使用 bulk_create 创建多对多关系
- iframe - 我们如何在 html 页面的 iframe 中显示linkedin 链接?
- python - 使用 stream.write 从流中回放
- python - 如何在 docker 中安装 PIP 和 PYMSSQL