( source: AsyncComponentLoader | AsyncComponentOptions )
| 40 | } |
| 41 | |
| 42 | export function defineAsyncComponent( |
| 43 | source: AsyncComponentLoader | AsyncComponentOptions |
| 44 | ): AsyncComponent { |
| 45 | if (isFunction(source)) { |
| 46 | source = { loader: source } |
| 47 | } |
| 48 | |
| 49 | const { |
| 50 | loader, |
| 51 | loadingComponent, |
| 52 | errorComponent, |
| 53 | delay = 200, |
| 54 | timeout, // undefined = never times out |
| 55 | suspensible = false, // in Vue 3 default is true |
| 56 | onError: userOnError, |
| 57 | } = source |
| 58 | |
| 59 | if (__DEV__ && suspensible) { |
| 60 | warn( |
| 61 | `The suspensiblbe option for async components is not supported in Vue2. It is ignored.` |
| 62 | ) |
| 63 | } |
| 64 | |
| 65 | let pendingRequest: Promise<Component> | null = null |
| 66 | |
| 67 | let retries = 0 |
| 68 | const retry = () => { |
| 69 | retries++ |
| 70 | pendingRequest = null |
| 71 | return load() |
| 72 | } |
| 73 | |
| 74 | const load = (): Promise<ComponentOrComponentOptions> => { |
| 75 | let thisRequest: Promise<ComponentOrComponentOptions> |
| 76 | return ( |
| 77 | pendingRequest || |
| 78 | (thisRequest = pendingRequest = |
| 79 | loader() |
| 80 | .catch((err) => { |
| 81 | err = err instanceof Error ? err : new Error(String(err)) |
| 82 | if (userOnError) { |
| 83 | return new Promise((resolve, reject) => { |
| 84 | const userRetry = () => resolve(retry()) |
| 85 | const userFail = () => reject(err) |
| 86 | userOnError(err, userRetry, userFail, retries + 1) |
| 87 | }) |
| 88 | } else { |
| 89 | throw err |
| 90 | } |
| 91 | }) |
| 92 | .then((comp: any) => { |
| 93 | if (thisRequest !== pendingRequest && pendingRequest) { |
| 94 | return pendingRequest |
| 95 | } |
| 96 | if (__DEV__ && !comp) { |
| 97 | warn( |
| 98 | `Async component loader resolved to undefined. ` + |
| 99 | `If you are using retry(), make sure to return its return value.` |
no test coverage detected
searching dependent graphs…