1. Write an asyncWrapper function so it is safe to say goodbye to the Promise then call with async await


export const asyncWrapper = (apiFn: (... args: any[]) =>Promise<any[]>) = > {
  return (data: any, config: any) = > new Promise((resolve) = > {
    apiFn(data, config).then(res= > {
      resolve([null, res])
    }).catch(error= > {
      resolve([error])
    })
  })
}

/ / use
const toGetuserInfo = async() = > {const [error, result] = await asyncWrapper(getUseApiFn)(id)
  if (error) {
    return
  }
  let userInfo = result.data.data
  / /...
}
Copy the code

2. Write a hook that uses a table

import { toRefs, reactive, ref } from "vue";
import { asyncWrapper } from "./asyncWrapper";

export const useTable = (request) = > {
  const state = reactive({
    tableData: [].loading: false
  })

  const getTableData = async(data = {}) => {
    state.loading = true;
    let [err, res] = await useApiWrapper(request)(data)
    state.loading = false;
    if (res.code === 0) { state.tableData = res.data; }};return {
    ...toRefs(state),
    getTableData,
  };
};


// setup
const { tableData, loading, getTableData } = useTable(request);
const query = reactive({
  field1: ' '.field2: ' '
})

const getDataFn = useApiWrapper(request)

onMounted(async() => { getTableData({... query}); });const reset = () = > {
  // do something ....
  query.field1 = ' '
  query.field2 = ' 'getTableData({... query}); };Copy the code

Encapsulate a piece of reusable form logic

export const useForm = (form, rules) = > {
  let{... copy} = formconst formRef = ref()
  form = reactive(form)

  const resetForm = () = > {
    Object.keys(copy).forEach(key= > form[key] = copy[key])
  }

  const setForm = (data) = > {
    Object.keys(data).forEach(key= > form[key] = data[key])
  }

  const formValidate = (formRef2) = > {
    let refObj = formRef2 || formRef
    return new Promise((resolve, reject) = > {
      refObj.value.validate((valid) = > {
        if (valid) {
          resolve(true)}else {
          resolve(false)}})})}return {
    form,
    formRef,
    rules,
    setForm,
    resetForm,
    formValidate,
  }
} 
Copy the code