如何在Elm lang中批量执行多个Http请求(任务) [英] How to perform multiple Http requests (Tasks) in bulk in Elm lang

查看:112
本文介绍了如何在Elm lang中批量执行多个Http请求(任务)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在将内容呈现到页面之前加载用户配置文件,但整个用户配置文件由多个HTTP请求加载的不同部分组成。

I want to load user profile before rendering something into the page but the whole user profile is composed of different parts that are loaded by multiple HTTP requests.

到目前为止我按顺序加载用户个人资料(逐个)

So far I'm loading user profile in sequence (one by one)

type alias CompanyInfo = 
  { name: String
  , address: ...
  , phone: String
  , ...
  }

type alias UserProfile = 
  { userName: String
  , companyInfo: CompanyInfo
  , ... 
  }

Cmd.batch
  [ loadUserName userId LoadUserNameFail LoadUserNameSuccess
  , loadCompanyInfo userId LoadCompanyInfoFail LoadCompanyInfoSuccess
  ...
  ]

但这不是很有效。有一个简单的方法如何执行一堆Http请求并返回一个完整的值?

But that's not very effective. Is there a simple way how to perform a bunch of Http requests and return just one complete value?

这样的东西

init = 
    (initialModel, loadUserProfile userId LoadUserProfileFail LoadUserProfileSuccess)

....


推荐答案

您可以使用来实现这一目标 Task.map2

You can achieve this using Task.map2:

编辑:已更新为Elm 0.18

Task.attempt LoadUserProfile <|
    Task.map2 (\userName companyInfo -> { userName = userName, companyInfo = companyInfo })
        (Http.get userNameGetUrl userDecoder |> Http.toTask)
        (Http.get companyInfoGetUrl companyInfoDecoder |> Http.toTask)

然后你可以摆脱个别的LoadUserName ......和LoadCompanyInfo ... Msgs。在Elm 0.18中,需要单独的Fail和Succeed Msgs Task.attempt 解决,期望结果错误消息类型,因此 LoadUserProfile 的定义如下:

You can then get rid of the individual LoadUserName... and LoadCompanyInfo... Msgs. In Elm 0.18, the need for separate Fail and Succeed Msgs is addressed by Task.attempt expecting a Result Error Msg type, so that LoadUserProfile is defined like this:

type Msg
    = ...
    | LoadUserProfile (Result Http.Error UserProfile)

map2 只有在两项任务都成功后才会成功。如果任何任务失败,它将失败。

map2 will only succeed once both tasks succeed. It will fail if any of the tasks fail.

这篇关于如何在Elm lang中批量执行多个Http请求(任务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆