The below code i use for doing multiple HTTP calls depending on the studentList
.
It works well; however, I think the axios spread is not necessary
export default {
getFee (studentList: { studentId: string }[]) {
if (studentList.length < 1) {
Promise.resolve()
}
let promises = []
for (const student of studentList) {
if (!student.studentId) {
Promise.resolve()
}
var url = `${API_URL}/${student.studentId}`
promises.push(Axios.get(url))
}
return Axios.all(promises)
.then(Axios.spread((...args) => {
// customise the response here
return args
.map(response => response.data)
.map(data => {
// @ts-ignore
data.totalMark = data.markinPhysics + data.markinMaths + data.markinChemistry // total mark sum of marks in differnet discplines
return data
})
}))
.catch(error => {
switch (error.response.status) {
case 400:
console.log('student not found')
break
case 500:
console.log('error invoking')
break
default:
console.log('unknown error')
I have to do multiple network calls in Vue and I am using Axios.
I got it working by axios, all and axios.spread, but I think the code can be improved.
The logic is to do multiple calls for the student list and get the outputs back
Can anyone help?
Since you're only using
args
as an array, you could removeaxios.spread
.axios.spread()
might only be useful in older browsers now that ES2015 introduced its own spread operator. The main purpose ofaxios.spread()
is to expand the result ofaxios.all()
into an argument list, such that you could do:instead of:
ES2015's rest operator does the inverse of
axios.spread()
, so when you combine them (as seen below), you end up with the result above, as ifaxios.spread()
and the rest operator weren't even used:To avoid promise chaining and improve readability, I think below can be used.