Axios实现多个并行请求

开发背景:

  项目需求是获取最近30天的顾客数据,而百度智客对应的接口一次只能获取某一天的顾客数据。也就是说,需要发送30个请求。

实现思路:

因为项目是用axios发送http请求的,所以首先想到了axios的方法:
concurrent requests

代码示例:

这里用jsonplaceholder中的数据,举例说明axios实现并行请求的方法。
function getPosts() {
  // 存储所有http请求
  let reqList = []
  // 存储后台响应每个请求后的返回结果
  let resList = []

  for(let i = 0; i< 30; i++) {
    let req = axios.get('https://jsonplaceholder.typicode.com/posts/' + (i + 1))
    
    reqList.push(req)
    resList.push(('post' + (i + 1)).replace(/[']+/g, ''))
  }

  return axios.all(reqList).then(axios.spread(function(...resList) {
    return resList // 拿到所有posts数据
  }))
}   

async function renderPage() {
  let posts = await getPosts()
  let docfrag = document.createDocumentFragment()

  for(let i = 0; i< posts.length; i++) {
    if (posts[i] && posts[i].status === 200) {
      let newLi = document.createElement('li')
      
      newLi.innerText = posts[i].data.title
      docfrag.appendChild(newLi)
    }
  }
  document.querySelector('.posts').appendChild(docfrag)
}

renderPage()

在线示例:

axios实现多个并行请求

你可能感兴趣的:(Axios实现多个并行请求)