Javascript 将调用localstorage的函数转换为异步等待
我有一个url,用户在使用Auth0签名后也会返回该url。当他们点击这个url时,我调用Javascript 将调用localstorage的函数转换为异步等待,javascript,async-await,Javascript,Async Await,我有一个url,用户在使用Auth0签名后也会返回该url。当他们点击这个url时,我调用auth.handleAuthentication() 在“我的反应”页面组件中: class AuthCallback extends React.Component { componentDidMount() { auth.handleAuthentication(); } 这是所调用的函数: handleAuthentication() { this.auth0.pars
auth.handleAuthentication()
在“我的反应”页面组件中:
class AuthCallback extends React.Component {
componentDidMount() {
auth.handleAuthentication();
}
这是所调用的函数:
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
} else if (err) {
console.error(err);
}
});
}
setSession(authResult) {
let expiresAt = JSON.stringify(
authResult.expiresIn * 1000 + new Date().getTime(),
);
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('AUTH_TOKEN', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
}
在handleAuthentication()
和setSession()
完成操作后,我需要异步执行一些操作
我尝试添加asyncwait
,但代码似乎是同步运行的
class AuthCallback extends React.Component {
async componentDidMount() {
await auth.handleAuthentication();
// DO STUFF
window.location.hash = '';
window.location.pathname = '/auth-callback-login';
}
只是包装了您需要等待返回承诺的函数
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
return resolve(authResult);
} else if (err) {
console.error(err);
reject(err);
}
});
});
那你就可以这么做了
class AuthCallback extends React.Component {
async componentDidMount() {
await auth.handleAuthentication();
// DO STUFF
window.location.hash = '';
window.location.pathname = '/auth-callback-login';
}
handleAuthentication
应该返回一个承诺
。所以我不需要在承诺中也加入setSession?嘿。。我对这个答案没有任何评论。只是想说一个好名字“onecompileman”xD~*主题音乐播放*~OneCompile~*主题仍在继续*~是的,@Evans,因为它并不是真正异步进行的。是的,OnePunchMan引用@DeadLock:)