Skip to content

Commit 2b38bea

Browse files
add Task.toResult
1 parent 36fe1c9 commit 2b38bea

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

platform/Task.roc

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ interface Task
1414
batch,
1515
seq,
1616
forEach,
17+
toResult,
1718
]
1819
imports [Effect, InternalTask]
1920

@@ -219,7 +220,7 @@ batch = \current -> \next ->
219220
## fetchAuthorTasks : List (Task Author [DbError])
220221
##
221222
## getAuthors : Task (List Author) [DbError]
222-
## getAuthors = Task.seq fetchAuthorTasks
223+
## getAuthors = Task.seq fetchAuthorTasks
223224
## ```
224225
##
225226
seq : List (Task ok err) -> Task (List ok) err
@@ -243,3 +244,32 @@ forEach : List a, (a -> Task {} b) -> Task {} b
243244
forEach = \items, fn ->
244245
List.walk items (InternalTask.ok {}) \state, item ->
245246
state |> await \_ -> fn item
247+
248+
## Transform a task that can succeed with `ok` or fail with `err` into a task
249+
## that always succeeds with a `Result ok err`.
250+
##
251+
## This is useful when chaining tasks using the `!` suffix.
252+
##
253+
## ```
254+
## # Path.roc
255+
## checkFile : Str -> Task [Good, Bad] [IOError]
256+
##
257+
## # main.roc
258+
## result =
259+
## checkFile "/usr/local/bin/roc"
260+
## |> Task.toResult!
261+
##
262+
## when result is
263+
## Ok Good -> "..."
264+
## Ok Bad -> "..."
265+
## Err IOError -> "..."
266+
## ```
267+
##
268+
toResult : Task ok err -> Task (Result ok err) *
269+
toResult = \task ->
270+
effect =
271+
Effect.after
272+
(InternalTask.toEffect task)
273+
\result -> result |> ok |> InternalTask.toEffect
274+
275+
InternalTask.fromEffect effect

0 commit comments

Comments
 (0)