【问题标题】:How to wait for the first arrived result on the thenable chain?如何在 thenable 链上等待第一个到达的结果?
【发布时间】:2023-04-05 12:51:01
【问题描述】:

我们可以使用Promise.race 等待thenable 链上第一个到达的结果。 Task 模块似乎还不支持它,Task.sequence 仅相当于 Promise.all

无法实现的解决方案演示:

import Process
import Task


init () =
    ( Nothing, Cmd.batch [ after 2 "2nd", after 1 "1st" ] )


after seconds name =
    Process.sleep (1000 * seconds)
        |> Task.map (always name)
        |> Task.perform Done


type Msg
    = Done String


update (Done name) model =
    case model of
        Nothing ->
            ( Debug.log name <| Just name, Cmd.none )

        _ ->
            ( Debug.log name model, Cmd.none )


main =  
    Platform.worker
        { init = init
        , update = update
        , subscriptions = always Sub.none
        }

运行它,按预期输出:

1st: Just "1st"
2nd: Just "1st"

【问题讨论】:

    标签: task elm elm-architecture


    【解决方案1】:

    Promise.race 作为一个独立的函数需要维护本地状态来跟踪它是否已经被解析,你可能知道这在 Elm 中是不可能的。

    但是您可以通过自己跟踪模型中的状态来相对轻松地完成相同的事情。下面是一个使用Maybe 跟踪我们是否收到回复的示例:

    type Thing =
        ...
    
    getThings : String -> Task Never (List Thing)
    getThings url =
        ...
    
    
    type alias Model =
        { things : Maybe (List Thing) }
    
    type Msg
        = GotThings (List Thing)
    
    
    init =
        ( { things = Nothing }
        , Cmd.batch 
              [ Task.perform GotThings (getThings "https://a-server.com/things")
              , Task.perform GotThings (getThings "https://a-different-server.com/things")
              ]
        )
    
    
    update msg model =
        case msg of
            GotThings things ->
                case model.things of
                    Nothing ->
                        ( { things = Just things }, Cmd.none )
    
                    Just _ ->
                        -- if we have already received the things, ignore any subsequent requests
                        ( model, Cmd.none )
    
    
    view model =
        ...
    

    【讨论】:

    • 用户应用程序可以描述其任何副作用的意图,其执行推迟到 elm 运行时。所以我认为像 Proimse.race 这样的函数可以但还可以由运行时实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2016-11-13
    • 2019-01-16
    • 2015-10-28
    • 2016-02-29
    相关资源
    最近更新 更多