将Auth0的parseHash函数包装在Promise中
auth0.js
具有用于解析URL哈希片段并从中提取身份验证结果的功能.我将此函数包装在一个称为loadSession
的函数中,如下所示:
auth0.js
has a function that's used to parse the URL hash fragment and extract the authentication result therefrom. I'm wrapping this function within one called loadSession
as follows:
public loadSession(): void {
this.auth0.parseHash((err, authResult) => {
if (authResult) {
window.location.hash = '';
localStorage.setItem('token', authResult.accessToken);
// TODO (1)
} else if (err) {
// TODO (2)
}
});
}
如上所示,parseHash
将回调函数作为参数,但我无法控制它.我想loadSession
返回一个Promise
,它将在// TODO (1)
处解析并在上述// TODO (2)
处被拒绝.这样我可以做obj.loadSession().then(() => { // do something if successful }).catch((err) => { // raise error if not })
As seen above, parseHash
takes a callback function as an argument and I cannot control that. I would like loadSession
to return a Promise
that would be resolved at // TODO (1)
and rejected at // TODO (2)
above. This way I can do obj.loadSession().then(() => { // do something if successful }).catch((err) => { // raise error if not })
只需将其包装在promise中:
Simply wrap it inside a promise:
public loadSession() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if(authResult) {
window.location.hash = '';
localStorage.setItem('token', authResult.accessToken);
resolve(authResult);
} else if (err) {
reject(err);
}
});
});
}