Tasks make it easy to describe asynchronous operations that may fail, like HTTP requests or writing to a database. For more information, see the Elm documentation on Tasks.
A task that succeeds immediately when run.
succeed 42 -- results in 42A task that fails immediately when run.
fail "file not found" : Task String aTransform a task.
map sqrt (succeed 9) -- succeed 3Put the results of two tasks together. If either task fails, the whole thing fails. It also runs in order so the first task will be completely finished before the second task starts.
map2 (+) (succeed 9) (succeed 3) -- succeed 12Chain together a task and a callback. The first task will run, and if it is successful, you give the result to the callback resulting in another task. This task then gets run.
succeed 2
|> andThen (\n -> succeed (n + 2))
-- succeed 4This is useful for chaining tasks together. Maybe you need to get a user from your servers and then lookup their picture once you know their name.
Start with a list of tasks, and turn them into a single task that returns a list. The tasks will be run in order one-by-one and if any task fails the whole sequence fails.
sequence [ succeed 1, succeed 2 ] -- succeed [ 1, 2 ]This can be useful if you need to make a bunch of HTTP requests one-by-one.
Recover from a failure in a task. If the given task fails, we use the callback to recover.
fail "file not found"
|> onError (\msg -> succeed 42)
-- succeed 42
succeed 9
|> onError (\msg -> succeed 42)
-- succeed 9Transform the error value. This can be useful if you need a bunch of error types to match up.
type Error = Http Http.Error | WebGL WebGL.Error
getResources : Task Error Resource
getResources =
sequence [ mapError Http serverTask, mapError WebGL textureTask ]The only way to do things in Elm is to give commands to the Elm runtime.
So we describe some complex behavior with a Task and then command the runtime
to perform that task. For example, getting the current time looks like this:
import Task
import Time exposing (Time)
type Msg = Click | NewTime Time
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Click ->
( model, Task.perform NewTime Time.now )
NewTime time ->
...Command the Elm runtime to attempt a task that might fail!
Represents asynchronous effects that may fail. It is useful for stuff like HTTP.
For example, maybe we have a task with the type (
Task String User). This means that when we perform the task, it will either fail with aStringmessage or succeed with aUser. So this could represent a task that is asking a server for a certain user.