【问题标题】:Need to await a function that is inside of a callback需要等待回调内部的函数
【发布时间】:2020-01-29 18:44:42
【问题描述】:

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

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

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

Root.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})`

【问题讨论】:

  • 当你发送setAuthToken时,它存储在哪里?
  • 如果handleLogin() 没有返回任何东西,这行(err, authResult) =&gt; handleLogin(err, authResult, this.props.dispatch) 怎么能成为你的parseHash() 函数的参数?

标签: javascript reactjs async-await react-redux auth0


【解决方案1】:

如果您使用redux thunk,那么调度将返回一个承诺。例如,您应该可以使用.then

handleLogin(err, authResult, this.props.dispatch).then(() => {/*other task code here*/})

您还需要从 handleLogin 函数返回调度

【讨论】:

  • 抱歉,@Ghojzilla,我不确定我是否理解。 handleLogin() 本身就是回调代码。理想情况下,我想让调用它的函数 parseHash() 异步,然后等待 handleLogin(),但是我没有对 parseHash() 函数的完全访问权限,因为它是一个内置的 Auth0 方法。
  • 当你说“在继续其他任务之前”你能把这些其他任务放在 .then 函数中吗?即使你把其他任务放在你从内部调用的函数中那么?如果您有可能,将编辑答案。
【解决方案2】:

const test = async () => {
  await example();
  console.log(`finished !`);
}

function example() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
}

test();

那么对于你的情况,我会说: 在异步函数中

// 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 可能保持为空。可能你的逻辑有问题。

记住:

(x) => x

等同于:

(x) => { return x; }

,带有箭头功能。

【讨论】:

  • 我已经尝试了一些变体,但随后出现错误:“'await' 表达式只允许在异步函数中使用。”将异步添加到包含函数也不起作用。
  • 我编辑了我的答案,现在应该可以尝试并告诉我@sthomas
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多