Home > @dinofe/xt-core > runWithDelayedLoading
# runWithDelayedLoading() function
带延迟加载提示的异步任务处理方法
Signature:
export declare function runWithDelayedLoading<T = any>(asyncTask: () => Promise<T>, { loadingDelay, minLoadingDuration, onLoading, onSettled, }?: IRunWithDelayedLoadingOptions): Promise<T>;
# Parameters
| Parameter | Type | Description | 
|---|---|---|
| asyncTask | () => Promise<T> | 任意异步任务函数,返回一个 Promise。 | 
| { loadingDelay, minLoadingDuration, onLoading, onSettled, } | IRunWithDelayedLoadingOptions | (Optional) | 
Returns:
Promise<T>
返回一个 Promise,该 Promise 会在异步任务完成(无论成功或失败)并等待加载提示结束才 Settled。
# Remarks
- 在设定的延迟时间内异步任务完成无加载提示;未完成时,触发加载提示;任务完成后,结束加载提示,且加载提示至少显示指定时长。 
- 返回的 Promise 与异步任务执行返回的 Promise 不同,但与其同时 Settled,自行对返回的 Promise 进行异常处理。 
# Example 1
调用 API 请求
<script setup lang="ts">
import { runWithDelayedLoading } from '@dinofe/xt-core/common'
import { useLoading } from "vue-loading-overlay"
const gloading = useLoading()
function onSubmit(formData) {
 runWithDelayedLoading(async () => {
   return Api.save(formData)
 }, {
   onLoading: () => {
     // show loading
     gloading.show()
   },
   onSettled: () => {
     // close loading
     gloading.hide()
   },
   minLoadingDuration: 3000
 }).then(() => {
   // success 至少等 3s 才弹出提示
   window.alert("保存成功")
 }).catch((e) => {
   // error
   window.alert("保存失败")
 })
}
</script>
# Example 2
立即开始 loading,异步任务结束立即结束 loading、立即处理异步任务结果
<script setup lang="ts">
import { runWithDelayedLoading } from '@dinofe/xt-core/common'
import { useLoading } from "vue-loading-overlay"
const gloading = useLoading()
function onSubmit(formData) {
 runWithDelayedLoading(async () => {
   return Api.save(formData)
 }, {
   onLoading: () => {
     // show loading
     gloading.show()
   },
   onSettled: () => {
     // close loading
     gloading.hide()
   },
   loadingDelay: 0,
   minLoadingDuration: 0
 }).then((res) => {
   if (res.code === 0) {
     window.alert("保存成功")
   } else {
     window.alert("保存失败")
   }
 }).catch((e) => {
   // error
   window.alert("保存失败")
 })
}
</script>
# Example 3
在异步任务结束时立即预渲染页面,此时 loading 的关闭比异步任务结束要晚
<script setup lang="ts">
import { runWithDelayedLoading } from '@dinofe/xt-core/common'
import { useLoading } from "vue-loading-overlay"
const gloading = useLoading()
const result = ref()
function onLoadInfo(id) {
 runWithDelayedLoading(async () => {
   return Api.info(id).then((res) => {
     // success 接口返回成功后立即使用结果预渲染页面
     result.value = res
   }).catch((e) => {
     console.log(e)
   })
 }, {
   onLoading: () => {
     // show loading
     gloading.show()
   },
   onSettled: () => {
     // close loading 等异步逻辑完成时展示预渲染的页面
     gloading.hide()
     showDetail()
   },
 })
}
function showDetail() {
  // your code...
}
</script>
