首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何改进axios.spread

如何改进axios.spread
EN

Stack Overflow用户
提问于 2019-05-13 16:29:09
回答 3查看 2K关注 0票数 2

下面的代码用于根据studentList执行多个HTTP调用。

它工作得很好,但是,我认为公理的传播是不必要的。

代码语言:javascript
复制
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。

我让它通过axios、all和axios.spread工作,但我认为代码可以改进。

其逻辑是对学生列表执行多次调用,并将输出返回

有人能帮忙吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-07-15 12:57:57

Axios.all

此外,Promise.all还接受一系列承诺,并返回一个新的承诺,每当所有给定的承诺都与一个数组一起解析时,该承诺就会被解析,并得到每个承诺的结果。

例如:

代码语言:javascript
复制
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将每个结果赋值给如下变量:

代码语言:javascript
复制
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分解分配

代码语言:javascript
复制
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方法没有影响,因为您没有返回它们

我的实现是什么?

代码语言:javascript
复制
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
}
票数 3
EN

Stack Overflow用户

发布于 2019-05-14 02:09:33

因为您只使用args作为数组,所以可以删除axios.spread

axios.spread()可能只在较旧的浏览器中有用,因为ES2015引入了自己的运算符axios.spread()的主要目的是将axios.all()的结果扩展到一个参数列表中,以便您可以这样做:

代码语言:javascript
复制
axios.all(promiseArray).then(axios.spread(function(arg1, arg2, arg3) {
  /*...*/
}))

而不是:

代码语言:javascript
复制
axios.all(promiseArray).then(function(args) {
  var arg1 = args[0]
  var arg2 = args[1]
  var arg3 = args[2]
  /*...*/
})

as 2015的运算符axios.spread()相反,所以当您将它们组合在一起(如下面所示)时,您将得到上面的结果,就好像axios.spread()和rest运算符甚至没有被使用一样:

代码语言:javascript
复制
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]
  /*...*/
}))
票数 2
EN

Stack Overflow用户

发布于 2019-05-20 12:05:31

为了避免许诺链接和提高可读性,我认为下面可以使用。

代码语言:javascript
复制
const [arg1, arg2] = await Promise.all(promises)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56116421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档