[英]Need to await a function that is inside of a callback
我正在使用 Auth0 在我的 React 应用程序中执行身份验证。
在 Auth0 获取信息后执行的默认重新路由时,我需要解析它返回的 hash,然后使用返回的一些将 auth Token 保存到商店以供以后执行其他任务。 然而,这个处理 authToken 存储的 function 发生在 parseHash(一个 auth0 函数)的回调中。
在继续其他任务之前,如何等待 handleLogin()(在回调中调用 function)完成? 我无法使 parseHash() 异步,因为我没有真正的访问权限。
根.tsx
`if (this.props.location.hash) {
this.props.authClient.parseHash(
{ hash: this.props.location.hash },
(err, authResult) => handleLogin(err, authResult, this.props.dispatch)
);
}
}`
处理登录.ts
`export const handleLogin = (
err: Auth0ParseHashError | null,
authResult: Auth0DecodedHash | null,
dispatch: Dispatch
) => {
if (authResult) {
const userId = authResult.idTokenPayload.sub;
dispatch(
setAuthToken({
token: {
accessToken: authResult.idToken,
userId
}
})
);
}
};`
这是从 Auth0 提供的关于 parseHash() 的信息
`parseHash(
options: ParseHashOptions,
callback: Auth0Callback<Auth0DecodedHash | null, Auth0ParseHashError>
): void;`
`Decodes the id_token and verifies the nonce.
@param callback: function(err, {payload, transaction})`
如果您使用的是redux thunk ,则调度将返回 promise。 你应该能够使用.then
例如
handleLogin(err, authResult, this.props.dispatch).then(() => {/*other task code here*/})
您还需要从您的handleLogin
function 返回调度
const test = async () => { await example(); console.log(`finished;`); } function example() { return new Promise((resolve) => { setTimeout(() => { resolve(), }; 2000); }); } test();
那么对于你的情况,我会说:在异步 function
// Async anonymous function that directly executes
(async() => {
const ret = await (err, authResult) => handleLogin(err, authResult, this.props.dispatch);
if (this.props.location.hash) {
this.props.authClient.parseHash(
{ hash: this.props.location.hash },
ret
);
}
})()
问题是, handleLogin()
似乎没有返回任何内容,因此ret
可能会保留 null。 可能你的逻辑有问题。
请记住:
(x) => x
是相同的:
(x) => { return x; }
, 带有箭头函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.