Skip to content

async await

daniel edited this page Sep 25, 2025 · 5 revisions
  • ex

呼叫主要程序後,再刷新畫面

methods: {
  async runMainTask() {
    try {
      const res = await this.$api.mainTask(params)
      if (res.success) {
        this.refreshViewData()
      }
    } catch (e) {
      this.$message.error('操作失敗')
    }
  },
  async refreshViewData() {
    const refreshRes = await this.$api.refreshView()
    this.tableData = refreshRes.data
  }
}

只改 setTeacherSpaceMode 成 async 不會讓它「自動等完再執行下一段」。

你還必須 await 它,並確保 saveSpace() 自己也是 async。

「在 async 裡面,能用 await 就不要用 .then()」

async + promise

// 保存空間設定
async saveSpace() {

  // ✅ 等待 setTeacherSpaceMode 完成
  await this.setTeacherSpaceMode();

  // ✅ 再進行手動分配的儲存動作
  if (this.autoMode === 'manual') {
    const params = {
      action: "upd",
      school_code: this.$store.state.userInfo.schoolCode,
      teachers: this.updTeachers
    }

    this.isLoading = true;

    try {
      const res = await this.$api.spaceAuth.teacherSpace(params);
      this.$Message.success(this.$t('teachermgmt.message.saveOk'));
      this.$store.commit('user/updTeacher', this.updTeachers);
      this.getTeachersTemp();
    } catch (err) {
      console.error(err);
    } finally {
      this.isLoading = false;
    }
  }
}
Clone this wiki locally