【问题标题】:Vue Reading in parallel in a loopVue循环并行读取
【发布时间】:2021-06-09 00:13:37
【问题描述】:

我有一个包含多个 Id 的 Set 数组。我想遍历 Set 并为每个 id 并行调用 api 并取回用户对象,将其添加到地图中。我该如何实现它。

值为设置 用户ID:设置[2] 0:“1” 1:“2”

 data() {
   return {
    userIds: new Set(), 
  };
},

 const res = getUsers(userId) 

【问题讨论】:

  • 编写声明性代码而不是凌乱的代码。正如您所想的那样,代码会很混乱。由于 javascript 是异步的,所以它是可以实现的。
  • 我想用多个id并行调用同一个api。你提到的上面的答案是不同的。

标签: vue.js


【解决方案1】:

希望它能解决您的问题。我没有测试,直接在这里写代码。

    // set requests
    let allRequests = []
    //you can use other loop based on your decession
    this.userIds.forEach(id => { allRequests.push(axios.get(`your_url\${id}`)) })
    
    // you can use await it is based on you requirement
    axios.all(allRequests).then(axios.spread((...responses) => {
      //make your map here using responses
    })).catch(errors => {
      // react on errors.
    })

你可以查看这个reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2020-05-04
    • 2013-08-15
    相关资源
    最近更新 更多