This repository was archived by the owner on Jan 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPromiseState.js
71 lines (61 loc) · 1.77 KB
/
PromiseState.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Record } from 'immutable';
export default class PromiseState extends Record({
state: 'INVALID',
payload: null,
}) {
static stateTypes = {
INVALID: 'INVALID',
LOADING: 'LOADING',
RESOLVED: 'RESOLVED',
REJECTED: 'REJECTED',
}
static INVALID = new PromiseState();
static LOADING = new PromiseState({state: PromiseState.stateTypes.LOADING});
static resolved = payload => new PromiseState({state: PromiseState.stateTypes.RESOLVED, payload});
static rejected = payload => new PromiseState({state: PromiseState.stateTypes.REJECTED, payload});
isInvalid() {
return this.state === PromiseState.stateTypes.INVALID;
}
isLoading() {
return this.state === PromiseState.stateTypes.LOADING;
}
isResolved() {
return this.state === PromiseState.stateTypes.RESOLVED;
}
isRejected() {
return this.state === PromiseState.stateTypes.REJECTED;
}
mapIf({
invalid = () => null,
loading = () => null,
resolved = () => null,
rejected = () => null,
}) {
switch (this.state) {
case PromiseState.stateTypes.INVALID:
return invalid();
case PromiseState.stateTypes.LOADING:
return loading();
case PromiseState.stateTypes.RESOLVED:
return resolved(this.payload);
case PromiseState.stateTypes.REJECTED:
return rejected(this.payload);
default:
throw new Error(`unknown state ${this.state}`);
}
}
mapIfResolved(f = payload => payload, valueIfNotResolved = null) {
if (this.isResolved()) {
return f(this.payload);
} else {
return valueIfNotResolved;
}
}
mapIfRejected(f = payload => payload, valueIfNotRejected = null) {
if (this.isRejected()) {
return f(this.payload);
} else {
return valueIfNotRejected;
}
}
}