JS 等待执行然后放置

时间:2021-04-08 01:08:21

标签: javascript async-await

我有以下代码,

    await getAuthFailedAttempts().then((attempt) => {
      errorMessage = VALIDATION_ERROR;

      if (!attempt.canRetry) {
        errorMessage = createFailedAttemptsError(attempt);
      } else {
        setAuthFailedAttempt();
      }

      this.setState({
        loading: false,
        passcode: "",
        validationError: errorMessage,
      });

那么如何重写以正确使用await,

    const attempt = await getAuthFailedAttempts();

以及如何为“尝试”放置“然后”?

提前致谢

1 个答案:

答案 0 :(得分:2)

您差不多已经完成了——一旦您使用 getAuthFailedAttempts()attempt 的结果分配给 await,那么您的 .then 的主体就是后面它:


const attempt = await getAuthFailedAttempts();
errorMessage = VALIDATION_ERROR;

if (!attempt.canRetry) {
  errorMessage = createFailedAttemptsError(attempt);
} else {
  setAuthFailedAttempt();
}

this.setState({
  loading: false,
  passcode: "",
  validationError: errorMessage,
});

请注意,要使用 await,包含的 function 必须是一个 async function 声明。

相关问题