Skip to content

Commit 39ecc3a

Browse files
author
SamLaptop
committed
Added check for async result
1 parent 15fc530 commit 39ecc3a

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

gitbook/asyncResult/check.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Result.check
2+
3+
Namespace: `FsToolkit.ErrorHandling`
4+
5+
The intent of check is to allow an Ok result value to be validated.
6+
7+
`check` takes a validation function of the form `'ok -> Async<Result<unit, 'error>>` and a result of the form `Async<Result<'ok, 'error>>`.
8+
9+
If the async-wrapped result is `Ok x` then the validation function is applied, and if the validation function returns an error, this new async-wrapped error is returned. Otherwise, the original async-wrapped `Ok x` result is returned. If the original async-wrapped result is an Error, the original async-wrapped result is returned.
10+
11+
## Function Signature
12+
```fsharp
13+
('ok -> Async<Result<unit,'error>>) -> Async<Result<'ok,'error>> -> Async<Result<'ok,'error>>
14+
```
15+
16+
## Examples
17+
18+
### Example 1
19+
20+
Given the following function that returns true for the id `123`
21+
```fsharp
22+
checkEnabled : int -> Async<bool>
23+
```
24+
25+
```fsharp
26+
AsyncResult.ok (
27+
{|
28+
PolicyId = 123
29+
AccessPolicyName = "UserCanAccessResource"
30+
|}
31+
32+
)
33+
|> AsyncResult.check (fun policy ->
34+
asyncResult {
35+
let! isEnabled = checkEnabled policy.PolicyId
36+
37+
return
38+
if not isEnabled then
39+
Error(
40+
$"The policy {policy.AccessPolicyName} cannot be used because its disabled."
41+
)
42+
else
43+
Ok()
44+
45+
}
46+
)
47+
// AsyncResult.Ok {| AccessPolicyName = "UserCanAccessResource"; IsEnabled = true; |}
48+
```
49+
50+
### Example 2
51+
52+
```fsharp
53+
AsyncResult.ok (
54+
{|
55+
PolicyId = 456
56+
AccessPolicyName = "UserCanAccessResource"
57+
|}
58+
59+
)
60+
|> AsyncResult.check (fun policy ->
61+
asyncResult {
62+
let! isEnabled = checkEnabled policy.PolicyId
63+
64+
return
65+
if not isEnabled then
66+
Error(
67+
$"The policy {policy.AccessPolicyName} cannot be used because its disabled."
68+
)
69+
else
70+
Ok()
71+
72+
}
73+
)
74+
75+
// AsyncResult.Error "The policy UserCanAccessResource cannot be used because its disabled."
76+
```

0 commit comments

Comments
 (0)