The Best Fluffy Pancakes recipe you will fall in love with. Full of tips and tricks to help you make the best pancakes.

怎麼把原有的程式頭尾加上想要執行的步驟,但又不影響原本的命名或是執行

封裝通用的請求處理函式

在開發上習慣把發出請求後加上畫面show mask,結束後hide mask,以防使用者在過程中的操作影響執行,但是在每個方法上的頭尾都要加show 、 hide,雖然複製很快,但是每個地方都要加上,久了會煩,程式碼一多就可能漏頭漏尾……

GPT :

你可以使用**高階函式(Higher-Order Function)**來封裝 proxy.$showLoading()proxy.$hideLoading(),這樣你的 storeupdatedestroy 這些方法就可以簡潔許多。


封裝通用的請求處理函式

const withLoading = async (fn) => {
  proxy.$showLoading();
  try {
    return await fn();
  } finally {
    proxy.$hideLoading();
  }
};

這個 withLoading 函式會:

  1. 在執行前 顯示 loading
  2. 執行傳入的函式(fn
  3. 無論成功或失敗 都會隱藏 loading(確保 proxy.$hideLoading() 一定會執行)

簡化你的 CRUD 方法

const store = () => withLoading(async () => {
  const payload = { data: { label: newLabel.value } };
  await crudStore.store(resource, payload);
});

const update = (data) => withLoading(async () => {
  const payload = { data: { label: data.label } };
  const id = data.uuid;
  await crudStore.update(resource, id, payload);
});

const destroy = (data) => withLoading(async () => {
  const id = data.uuid;
  await crudStore.destroy(resource, id);
  index();
});

這樣你的 storeupdatedestroy 方法就不需要每次手動加 proxy.$showLoading()proxy.$hideLoading(),所有請求都會自動處理 Loading 效果。


呼叫方式不變

你的其他程式碼仍然可以像之前一樣使用:

store();
update(someData);
destroy(someData);

這樣就達成了 程式碼簡潔化,還能確保 loading 效果正確執行!🚀

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *