-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
39 lines (35 loc) · 1.05 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { mountTaskMethodToPromise, noop } from '../utils';
import { RequestPromise } from '../types';
/**
* 发起网络请求
*
* 文档 http://uniapp.dcloud.io/api/request/request?id=request
*/
export function request<T = UniApp.RequestSuccessCallbackResult>(
urlOrOptions: string | UniApp.RequestOptions,
options?: UniApp.RequestOptions,
) {
const _options =
typeof urlOrOptions === 'string'
? { ...options, url: urlOrOptions, complete: options?.complete ?? noop }
: {
...urlOrOptions,
...options,
complete: urlOrOptions?.complete ?? options?.complete ?? noop,
};
const { success, fail } = _options;
let task: UniApp.RequestTask | undefined;
const promise: RequestPromise<T> = new Promise((resolve, reject) => {
_options.success = (r) => {
success?.(r);
resolve(r);
};
_options.fail = (e) => {
fail?.(e);
reject(e);
};
task = uni.request(_options);
}) as unknown as RequestPromise<T>;
mountTaskMethodToPromise<T>(task, promise);
return promise;
}