-
Notifications
You must be signed in to change notification settings - Fork 0
/
p-if.ts
40 lines (38 loc) · 1.17 KB
/
p-if.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
/**
* @packageDocumentation
* @module @tomato-js/async
*/
import { isFunction } from "@tomato-js/shared";
/**
* 有条件的promise链
*
* 新增于v0.0.15
*
* 脚本举例
* ```
* import { pIf } from '@tomato-js/async'
* Promise.resolve([]).then(pIf(condition(), () => "if",()=>"else")).then;
* Promise.resolve([]).then(pIf(true, () => "if").then();
* ```
*
* @param condition - 判断条件
* @param doIf - true时后续逻辑函数
* @param doElse - false时后续逻辑函数
* @returns promise
*/
export function pIf<ValueType, DoIfRetureType, DoElseReturnType>(
condition: boolean | ((value: ValueType) => boolean | PromiseLike<boolean>),
doIf: (value: ValueType) => DoIfRetureType | PromiseLike<DoElseReturnType>,
doElse?: (value: ValueType) => DoElseReturnType | PromiseLike<DoElseReturnType>
) {
return async function(value: ValueType) {
async function chooseFn(boolean: boolean) {
return boolean === true ? await doIf(value) : doElse ? await doElse(value) : value;
}
if (isFunction(condition)) {
const conditionResult = await condition(value);
return chooseFn(conditionResult);
}
return chooseFn(condition);
};
}