javascript - 需要等待回调内的函数

标签 javascript reactjs async-await react-redux auth0

我正在使用 Auth0 在我的 React 应用程序中执行身份验证。

在 Auth0 在获取信息后执行默认重新路由时,我需要解析它返回的哈希,然后使用一些返回的哈希将身份验证 token 保存到存储中以供稍后执行其他任务。然而,这个处理 authToken 存储的函数发生在 parseHash(auth0 函数)的回调中。

如何等待handleLogin()(回调中调用的函数)完成后再继续其他任务?我无法使 parseHash() 异步,因为我没有真正访问它。

根.tsx

`if (this.props.location.hash) {
      this.props.authClient.parseHash(
        { hash: this.props.location.hash },
        (err, authResult) => handleLogin(err, authResult, this.props.dispatch)
      );
    }
  }`

handleLogin.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 函数返回调度

关于javascript - 需要等待回调内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168446/

相关文章:

javascript - 在ajax中获取响应参数值

javascript - highcharts 中具有多个 ID 的 linkedTo

javascript - 如何在我的 react slider 中设置显示柔性?

node.js - React 项目 - 对 ExpressJS 服务器的请求返回 400 - 错误请求

c# - 在 "await DownloadTaskAsync"上调用 WebClient.CancelAsync 时出现 WebException

javascript - 通过根据需要旋转数据库或模拟来进行测试?

Php 将数组传递给 Javascript

javascript - Polymer 1.x 和 React

javascript - 如何在 google 和 API 的操作中使用 async 和 wait

c# - Task.WhenAll 订单的结果有保证吗?