我有以下代码,
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();
以及如何为“尝试”放置“然后”?
提前致谢
答案 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
声明。