-
Notifications
You must be signed in to change notification settings - Fork 0
/
andThen.ts
54 lines (49 loc) · 1.49 KB
/
andThen.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type { MaybePromise, ResultReturnValue } from '@/types'
import { isPromise } from '@/utils'
import type { Result } from './result'
import { err } from './result'
/**
* Call `fn` if `result` is success.
*
* @example
* ```typescript
* const userInfo = (await andThen(queryUserInfo, ok(userId))).unwrap()
* // with flow
* const userInfo = (await flow(ok(userId), andThen(queryUserInfo))).unwrap()
* ```
*
* {@link https://github.com/niuiic/fx-flow/blob/main/packages/test/src/flow/andThen.spec.ts | More examples}
*/
function andThen<A, R extends MaybePromise<Result<unknown>>>(
fn: (data: A) => R,
result: Result<A>
): ResultReturnValue<R>
function andThen<A, R extends MaybePromise<Result<unknown>>>(
fn: (data: A) => R
): (result: Result<A>) => ResultReturnValue<R>
function andThen<A, R extends MaybePromise<Result<unknown>>>(
fn: (data: A) => R,
result?: Result<A>
): ResultReturnValue<R> | ((result: Result<A>) => ResultReturnValue<R>) {
if (result === undefined) {
return (result) => andThen(fn, result)
}
if (result.isOk()) {
const res = fn(result.unwrap())
if (isPromise(res)) {
return res.then((result) => {
if (result.isPromise()) {
return result.wait()
}
return result
}) as ResultReturnValue<R>
} else {
if (res.isPromise()) {
return res.wait() as ResultReturnValue<R>
}
return res as ResultReturnValue<R>
}
}
return err(result.error()!) as ResultReturnValue<R>
}
export { andThen }