【问题标题】:Two sequential HTTP requests两个连续的 HTTP 请求
【发布时间】:2014-11-03 11:25:17
【问题描述】:

抱歉新手的问题(以及我的英语):)

我尝试编写以下函数:

  • 函数从 URL1 下载内容(作为参数接收)
  • 函数解析此内容并提取URL2
  • 函数从 URL2 下载内容
  • URL2 中的内容是这个函数的结果
  • 如果发生错误,此函数应返回 Nothing

我知道如何执行 HTTP 请求。我有一个函数来解析来自 URL1 的请求。但我不知道怎么做:

  • 使用提取的 URL2 执行新请求
  • 如果 URL2 未提取(或 URL1 发生错误)则忽略第二个请求

【问题讨论】:

    标签: frp elm


    【解决方案1】:

    我原则上你想要这样的东西:

    import Maybe
    import Http
    
    type Url = String
    getContentFromUrl : Maybe Url -> Maybe String
    getContentFromUrl url = --your implementation
    extractUrlFromContent : Maybe String -> Maybe Url
    extractUrlFromContent content = --your implementation
    content = getContentFromUrl (Just "http://example.com") 
              |> extractUrlFromContent 
              |> getContentFromUrl
    

    【讨论】:

    • 你的回答很有用。谢谢
    【解决方案2】:

    发送 Http 意味着与外界对话,这涉及到 Elm 中的Signals。因此,来自 URL2 的最终结果将包含在 Signal 中。只要您对此感到满意,您就可以使用可能在Signal 中返回Maybe 中的内容。例如:

    import Maybe
    import Http
    
    -- helper functions
    isSuccess : Http.Response a -> Bool
    isSuccess response = case response of
      Http.Success _ -> True
      _              -> False
    
    responseToMaybe : Http.Response a -> Maybe.Maybe a
    responseToMaybe response = case response of
      Http.Success a -> Just a
      _              -> Nothing
    
    parseContentAndExtractUrl : String -> String
    parseContentAndExtractUrl = identity -- this still requires your implementation
    
    -- URL1
    startUrl : String
    startUrl = "www.example.com" -- replace this with your URL1
    
    result1 : Signal (Http.Response String)
    result1 = Http.sendGet <| constant startUrl
    
    -- URL2
    secondUrl : Signal String
    secondUrl = result1
      |> keepIf isSuccess (Http.Success "")
      |> lift (\(Http.Success s) -> s)
      |> lift parseContentAndExtractUrl
    
    result2 : Signal (Maybe String)
    result2 = secondUrl
      |> Http.sendGet
      |> lift responseToMaybe
    

    请注意,我们有计划让所有这些操作更容易:https://groups.google.com/d/topic/elm-discuss/BI0D2b-9Fig/discussion

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 2012-02-06
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多