How to Improve The axios.spread

2019-05-28 22:44发布

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?

标签: vuejs2 axios
2条回答
Anthone
2楼-- · 2019-05-28 22:55

Since you're only using args as an array, you could remove axios.spread.

axios.spread() might only be useful in older browsers now that ES2015 introduced its own spread operator. The main purpose of axios.spread() is to expand the result of axios.all() into an argument list, such that you could do:

axios.all(promiseArray).then(axios.spread(function(arg1, arg2, arg3) {
  /*...*/
}))

instead of:

axios.all(promiseArray).then(function(args) {
  var arg1 = args[0]
  var arg2 = args[1]
  var arg3 = args[2]
  /*...*/
})

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 if axios.spread() and the rest operator weren't even used:

axios.all(promiseArray).then(axios.spread(function(...args) {
  var arg1 = args[0]
  var arg2 = args[1]
  var arg3 = args[2]
  /*...*/
}))

// or newer syntax:

axios.all(promiseArray).then(axios.spread((...args) => {
  const arg1 = args[0]
  const arg2 = args[1]
  const arg3 = args[2]
  /*...*/
}))
查看更多
仙女界的扛把子
3楼-- · 2019-05-28 23:04

To avoid promise chaining and improve readability, I think below can be used.

const [arg1, arg2] = await Promise.all(promises)
查看更多
登录 后发表回答