如何改善axios.spread [英] How to Improve The axios.spread

查看:190
本文介绍了如何改善axios.spread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码根据studentList用于执行多个HTTP调用.

The below code i use for doing multiple HTTP calls depending on the studentList.

效果很好;但是,我认为axios的传播不是必须的

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')

我必须在Vue中进行多个网络通话,而我正在使用Axios.

I have to do multiple network calls in Vue and I am using Axios.

我让axios,all和axios.spread都可以使用它,但是我认为代码可以改进.

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

任何人都可以帮忙吗?

推荐答案

Axios.all

以及 Promise.all 接受promise数组并返回一个新的Promise,只要使用数组以每个promise的结果来解析所有给定的promise,该promise就会被解决

Axios.all

as well as Promise.all accepts array of promises and returns a new Promise which is resolved whenever all of the given promises are resolved with an array with the result of each promise

例如

const promise1 = Promise.resolve('data1');
const promise2 = Promise.resolve('data2');

Promise.all([
  promise1,
  promise2,
]).then(results => {
  // results is an array with 2 elements
  console.log(results[0]); // data1
  console.log(results[1]); // data2
});

您可以使用Axios.spread将每个结果分配给这样的变量:

you can use Axios.spread to to assign each result to a variable like this:

Promise.all([
  promise1,
  promise2,
]).then(Axios.spread(( result1, result2 ) => {
  // args is an array with 2 elements
  console.log(result1); // data1
  console.log(result2); // data2
});

或者,您可以使用 ES6破坏性分配:

Promise.all([
  promise1,
  promise2,
]).then(([ result1, result2 ]) => {
  // args is an array with 2 elements
  console.log(result1); // data1
  console.log(result2); // data2
});

不必要的Promise.resolve()

您的Promise.resolve()函数调用对getFee方法没有影响,因为您没有返回它们

Unnecessary Promise.resolve()

Your Promise.resolve() function calls have no effect on the getFee method since you're not returning them

async function getFee(studentList) {
  try {
    const promises = studentList.reduce((acc, student) =>
      student.studentId
        ? acc.concat(Axios.get(`${API_URL}/${student.studentId}`))
        : acc
    , []);

    const responses = await Axios.all(promises);

    return responses
      .map(response => response.data)
      .map(data => ({
        // return new object
        // with data's properties
        // instead of assinging the new ones directly to the data
        ...data,
        // total mark  sum of marks in differnet discplines
        totalMark: data.markinPhysics + data.markinMaths + data.markinChemistry,
      }));
  } 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");
    }
  }
}

export default {
  getFee
}

这篇关于如何改善axios.spread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆