Skip to content

Commit f25ac03

Browse files
authored
Merge pull request #51 from TeamVastsea/fix-use-async-for-finish
feat: 将保存和下一页函数改为异步,以支持更好的错误处理
2 parents 822e5d1 + 01c36d7 commit f25ac03

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

app/(root)/survey/[id]/page.tsx

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export default function SurveyPage({ params }: { params: { id: number } }) {
2727

2828
// const answerId = useRef(searchParams.get('answer'));
2929

30-
function save() {
30+
async function save() {
3131
if (questions == null) {
3232
return false;
3333
}
@@ -39,11 +39,11 @@ export default function SurveyPage({ params }: { params: { id: number } }) {
3939
for (const question of questions) {
4040
// 检查题目是否可见(满足条件)
4141
const isVisible = checkAccess(JSON.stringify(question.condition));
42-
42+
4343
// 如果题目可见且为必填题
4444
if (isVisible && question.required) {
4545
const answer = answers.get(question.id);
46-
46+
4747
// 检查答案是否为空
4848
if (!answer || answer.trim() === '' || answer === '[]') {
4949
hasUnfilledRequired = true;
@@ -62,20 +62,22 @@ export default function SurveyPage({ params }: { params: { id: number } }) {
6262
return false;
6363
}
6464

65-
ScoreApi.submitAnswer({
66-
id: answerId,
67-
survey: Number(params.id),
68-
content: Object.fromEntries(answers),
69-
})
70-
.then((res) => {
71-
setAnswerId(res);
65+
try {
66+
const res = await ScoreApi.submitAnswer({
67+
id: answerId,
68+
survey: Number(params.id),
69+
content: Object.fromEntries(answers),
7270
});
73-
74-
return true;
71+
setAnswerId(res);
72+
return true;
73+
} catch (error) {
74+
return false;
75+
}
7576
}
7677

77-
function nextPage() {
78-
if (!save()) {
78+
async function nextPage() {
79+
const saved = await save();
80+
if (!saved) {
7981
return;
8082
}
8183

@@ -92,15 +94,23 @@ export default function SurveyPage({ params }: { params: { id: number } }) {
9294
return;
9395
}
9496

95-
ScoreApi.finishAnswer(answerId).then(() => {});
97+
try {
98+
await ScoreApi.finishAnswer(answerId);
9699

97-
notifications.show({
98-
title: '提交成功',
99-
message: '试卷已成功提交',
100-
color: 'green',
101-
});
100+
notifications.show({
101+
title: '提交成功',
102+
message: '试卷已成功提交',
103+
color: 'green',
104+
});
102105

103-
router.push(`/survey/${params.id}/completed?fs=true`);
106+
router.push(`/survey/${params.id}/completed?fs=true`);
107+
} catch (error) {
108+
notifications.show({
109+
title: '提交失败',
110+
message: '试卷提交时发生错误,请重试',
111+
color: 'red',
112+
});
113+
}
104114
}
105115

106116
function prevPage() {

0 commit comments

Comments
 (0)