如何实现和 return 一个 Cmd Msg?

How do I implement and return a Cmd Msg?

如何实施和return Cmd Msg?

例如,以下行生成一个 Cmd Msg:

Http.send msg request

在以下函数中使用:

tryRegister : Form -> (Result Http.Error JsonProfile -> msg) -> Cmd msg
tryRegister form msg =
    let
        registerUrl =
            "http://localhost:5000/register"

        body =
            encode form |> Http.jsonBody

        request =
            Http.post registerUrl body decoder
    in
        Http.send msg request

我正在尝试在我的 TestAPI 中编写类似函数的代码:

tryRegister : Form -> (Result Http.Error JsonProfile -> msg) -> Cmd msg
tryRegister form msg =
    Cmd.none

以上代码编译通过。但是,我不清楚如何实现 return 不是 Cmd.none.

的 Cmd Msg 的功能

附录:

type Msg
    =
    ...
    | Submit
    | Response (Result Http.Error JsonProfile)

update : Msg -> Form -> ( Form, Cmd Msg )
update msg model =
    case msg of
       ...
       Submit ->
           ( model, runtime.tryRegister model Response )

Source code on GitHub.

编辑

最初的答案建议映射到 Cmd.none,它可以编译并且在模拟函数进行测试时可能会有用,但如果你真的试图在 Elm 架构中强制另一个 update 循环,您将需要转换为 Task,如 send 函数 described here.

中所述
send : msg -> Cmd msg
send msg =
    Task.succeed msg
        |> Task.perform identity

正如@SwiftsNamesake 上面提到的,在大多数情况下这是没有必要的,关于这个主题的整个博客 post 是 worth a read.

原答案

您可以使用 Cmd.map 而不是 Cmd.none 将其更改为任何 Cmd:

Cmd.map (always Submit) Cmd.none