代码之家  ›  专栏  ›  技术社区  ›  sof

如何在表链上等待第一个到达的结果?

  •  2
  • sof  · 技术社区  · 7 年前

    我们可以用 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"
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   glennsl Namudon'tdie    7 年前

    Promise.race

    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 =
        ...
    
    推荐文章