開(kāi)發(fā)背景:
項(xiàng)目需求是獲取最近30天的顧客數(shù)據(jù)坤按,而百度智客對(duì)應(yīng)的接口一次只能獲取某一天的顧客數(shù)據(jù)。也就是說(shuō)馒过,需要發(fā)送30個(gè)請(qǐng)求臭脓。
實(shí)現(xiàn)思路:
因?yàn)轫?xiàng)目是用axios發(fā)送http請(qǐng)求的,所以首先想到了axios的方法:
代碼示例:
這里用jsonplaceholder中的數(shù)據(jù)腹忽,舉例說(shuō)明axios實(shí)現(xiàn)并行請(qǐng)求的方法来累。
function getPosts() {
// 存儲(chǔ)所有http請(qǐng)求
let reqList = []
// 存儲(chǔ)后臺(tái)響應(yīng)每個(gè)請(qǐng)求后的返回結(jié)果
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數(shù)據(jù)
}))
}
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()