{"id":238,"date":"2025-02-01T11:40:00","date_gmt":"2025-02-01T03:40:00","guid":{"rendered":"https:\/\/mitongxue.cn\/?p=238"},"modified":"2026-06-05T12:59:40","modified_gmt":"2026-06-05T04:59:40","slug":"useasync-%e5%b0%81%e8%a3%85","status":"publish","type":"post","link":"https:\/\/mitongxue.cn\/index.php\/2025\/02\/01\/useasync-%e5%b0%81%e8%a3%85\/","title":{"rendered":"useAsync \u5c01\u88c5"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>import { shallowRef, ref, watchEffect, unref } from \"vue\";\nimport type { Ref } from \"vue\";\n\ninterface UseAsyncOptions&lt;T, Params extends any&#91;]> {\n  immediate?: boolean;\n  shallow?: boolean;\n  params?: Params;\n  onError?: (err: unknown) => void;\n  onSuccess?: (data: T) => void;\n  onBefore?: () => void;\n}\n\ninterface UseAsyncReturn&lt;T, Params extends any&#91;]> {\n  data: Ref&lt;T | undefined>;\n  loading: Ref&lt;boolean>;\n  error: Ref&lt;unknown>;\n  execute: (...args: Params) => Promise&lt;T | undefined>;\n}\n\nexport function useAsync&lt;T, Params extends any&#91;] = &#91;]>(\n  fn: (...args: Params) => Promise&lt;T>,\n  options: UseAsyncOptions&lt;T, Params> = {}\n): UseAsyncReturn&lt;T, Params> {\n  const {\n    immediate = true,\n    shallow = false,\n    params = &#91;] as unknown as Params,\n    onError,\n    onSuccess,\n    onBefore,\n  } = options;\n\n  const data = shallow ? shallowRef&lt;T>() : ref&lt;T>();\n  const loading = ref(false);\n  const error = ref&lt;unknown>();\n\n  const execute = async (...args: any) => {\n    try {\n      loading.value = true;\n      error.value = null;\n      onBefore &amp;&amp; onBefore();\n\n      const response = await fn(...args);\n      data.value = response;\n\n      onSuccess &amp;&amp; onSuccess(response);\n\n      return response;\n    } catch (err) {\n      error.value = err;\n      onError &amp;&amp; onError(err);\n      return undefined;\n    } finally {\n      loading.value = false;\n    }\n  };\n\n  if (immediate) {\n    watchEffect(() => {\n      if (params) {\n        execute(params);\n      }\n    });\n  }\n\n  return {\n    data,\n    loading,\n    error,\n    execute,\n  };\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u4f7f\u7528<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useAsync } from \"@\/composables\/useAsync\";\n\nconst option = ref({})\n\n\/\/ const state = ref&lt;Sales&#91;]>(&#91;]);\n\n\/\/ const getData = () => { \n\/\/   getSalesList().then(res => { \n\/\/     if (res.code === 200) { \n\/\/       state.value = res.data!;\n\/\/       setOption();\n\/\/     }\n\/\/   })\n\/\/ }\n\n\/\/ onMounted(() => { \n\/\/   getData();\n\/\/ })\n\n\nconst { data:state, loading } = useAsync(getSalesList, {\n  onSuccess: (res) => {\n    console.log('\u9500\u552e\u6570\u636e\u52a0\u8f7d\u6210\u529f',res);\n    \/\/ state.value = res.data!;\n    if (res.code === 200) { \n      setOption(res.data!);\n    }\n  },\n  onError: (err) => { \n    console.error('\u9500\u552e\u6570\u636e\u52a0\u8f7d\u5931\u8d25',err);\n  }\n})\n\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u4f7f\u7528<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,13,11],"tags":[],"class_list":["post-238","post","type-post","status-publish","format-standard","hentry","category-js","category-vue","category-front"],"featured_image_urls":{"full":"","thumbnail":"","medium":"","medium_large":"","large":"","1536x1536":"","2048x2048":""},"author_info":{"info":["\u9648 \u67d0\u4eba"]},"category_info":"<a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/js\/\" rel=\"category tag\">JS<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/vue\/\" rel=\"category tag\">Vue<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/front\/\" rel=\"category tag\">\u524d\u7aef<\/a>","tag_info":"\u524d\u7aef","comment_count":"0","_links":{"self":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/238","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/comments?post=238"}],"version-history":[{"count":1,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/238\/revisions"}],"predecessor-version":[{"id":240,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/238\/revisions\/240"}],"wp:attachment":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/media?parent=238"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/categories?post=238"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/tags?post=238"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}