首页 > 解决方案 > How to chain port calls?

问题描述

port createNewDocument: Encode.Value -> Cmd msg 
port printDocument : () -> Cmd msg
createNewDocument: Document -> Task err msg
printDocument: Task err msg

i want to chain this create and print steps, in one step. Because sometimes i need both one after another - some other times i need to create the document - make some updates, then print.

someCmd: Cmd msg
someCmd = createNewDocument |> Task.andThen (\ what? -> -- what to add here? printDocument ) |> Task.attempt (\ result -> some result handler )

how can i chain port calls? Because ports return Cmd msg not Task err msg.

标签: portelm

解决方案


如果不引入中间的信息,就无法做到这一点。端口也只是单向的,因此您需要订阅端口才能从外部源返回值。

即:您的第一个命令触发了一个 JavaScript 函数,该函数通过订阅发送消息,并且在您的update函数中,您通过返回第二个命令来处理该消息。

type Msg
    = ...
    | CreateNewDocument Encode.Value
    | PrintDocument Document

update : Msg -> Model -> (Model, Cmd.model)
update msg model =
    case msg of 
        ...

        CreateNewDocument value ->
            (model, createNewDocument value)

        PrintDocument document -> 
            (model, printDocument document)

sub : Sub Msg
sub = 
   receiveNewDocument PrintDocument

推荐阅读