【问题标题】:Axios-Make multiple request at once (vue.js)Axios-一次发出多个请求(vue.js)
【发布时间】:2018-11-05 11:53:31
【问题描述】:

如何使用 axios 和 vue 并行发出多个请求?

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    您可以将异步调用传递给 Promise.all。 只要他们每个人都返回一个承诺,他们就会同时执行。 我正在使用 store.dispatch,但您同样可以使用 axios 调用或 fetch。

    在这个例子中,我在创建 vue 组件时进行调用:

    ...
    async created() {
        const templates = this.$store.dispatch(TEMPLATES_LOAD);
        const userTemplates = this.$store.dispatch(USER_TEMPLATES_LOAD);
        const players = this.$store.dispatch(OTHER_PLAYERS_LOAD);
        return await Promise.all([templates, userTemplates, players])
            .then(() => {
                console.log('Loaded data for form elements');
            });
    }
    

    【讨论】:

      【解决方案2】:

      因为 axios 可以被 React 和 Vue 使用,所以代码几乎是一样的。

      请务必阅读axios docs,您可以从那里了解。

      不管怎样,我给你举个例子:

      <template>
        <div>
         <button @click="make_requests_handler">Make multiple request</button>
         {{message}} - {{first_request}} - {{second_request}}
        </div>
      </template>
      

      还有脚本:

      import axios from 'axios'
      
      export default {
        data: () => ({
          message: 'no message',
          first_request: 'no request',
          second_request: 'no request'
        }),
        methods: {
          make_requests_handler() {
            this.message = 'Requests in progress'
      
            axios.all([
              this.request_1(), //or direct the axios request
              this.request_2()
            ])
          .then(axios.spread((first_response, second_response) => {
                this.message = 'Request finished'
                this.first_request = 'The response of first request is' + first_response.data.message
                this.second_request = 'The response of second request is' + second_response.data.message
              }))
          },
          request_1() {
           this.first_request: 'first request began'
           return axios.get('you_URL_here')
          },
          request_2() {
            this.second_request: 'second request began'
            return axios.get('another_URL', { params: 'example' })
          }
        }
      }
      

      【讨论】:

      • 谢谢你帮了我很多!
      • 如果有人在 2020+ 年阅读此内容...axios.all 可能未定义。请改用原生 ES6 Promise.all
      • 另外应该提到的是,OP 没有直接要求同步并行调用的结果(尽管这显然是他/她正在寻找的)。 “并行请求”也可能意味着从同一个处理程序启动多个异步调用,并在每个结果进入时单独处理它。根据用例(即调用及其结果的使用是独立的),这将提高应用程序的性能,而使用 all 将延迟较快的调用,直到最慢的调用完成。
      • @Terry axios.all 怎么可能是未定义的? @dr_barto 我不明白你的意思。答案提供了一个解决方案,因此两个请求将并行执行并在它们都完成时解决。在then 块中,您可以处理这两个响应。在这里阅读更多 -> github.com/axios/axios/issues/371
      • 只是建立在 dr_barto 之上 - 因为这些是异步调用,它们已经自动并行发生。如果您需要在运行某些代码之前等待所有请求完成,您只想依赖 Promise.all。不过,最好在可能的情况下将每个请求/组件的关注点分开。
      猜你喜欢
      • 2019-03-07
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2018-06-16
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      相关资源
      最近更新 更多