A
A
aheles2021-11-01 14:57:25
Vue.js
aheles, 2021-11-01 14:57:25

Vue+js how to make axios execute one by one?

There is a function that sends axios:

getSchedules(locationId, gameModeId, selectedHeadsets, day) {

                let param = 'locationId=' + locationId + '&gameModeId=' + gameModeId + '&headsets=' + selectedHeadsets

                if (day)
                    param += '&day=' + day;

                return axios({
                    method: 'get',
                    url: 'schedules?' + param
                }).then((response) => {


                    if(this.curDateEvent){
                        this.changeMobileDay(this.curDateEvent);
                    }

                }).catch((error) => {

                });
            }


The problem is that if the user sent a request many times, then data is returned to him that is not loaded one by one, for example, a person sent 5 requests at once, but for example, the last request will load faster than the fourth request. How to sequence requests?
Googled it, found out about async await, but could not substitute it into the function
. An example of calling this function itself:
this.getSchedules(this.selectedLocationId, this.selectedGameModeId, this.selectedHeadsets,day).then(()=>{
document. getElementById('stepView4').scrollIntoView({behavior:'smooth'});
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-11-01
@aheles

If this is exactly what you want, then you can make yourself a queue, conditionally like this:

class AsyncQueue {
  constructor(result) {
    this.queue = [];
    this.result = result;
  }
  isStreaming = false;
  add(promise) {
    this.queue.push(promise);
    if(!this.isStreaming)
      this.stream();
  }
  async stream() {
    this.isStreaming = true;
    for await (const result of this.queue) {
      this.result(result);
    }
    this.queue.length = 0;
    this.isStreaming = false;
  }
}

vue:
data() {
  const schedulesQueue = new AsyncQueue(this.showLoadedSchedules);
  return {
    schedulesQueue,
    // ...
  }
},

methods: {
  showLoadedSchedules(response) {
    if(this.curDateEvent) {
      this.changeMobileDay(this.curDateEvent);
    }
    // ...
  },
  addSchedulesToQueue(locationId, gameModeId, selectedHeadsets, day) {
    let param = 'locationId=' + locationId + '&gameModeId=' + gameModeId + '&headsets=' + selectedHeadsets

    if (day)
      param += '&day=' + day;

    return this.schedulesQueue.add(
      axios({
        method: 'get',
        url: 'schedules?' + param
      }).catch((error) => {})
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question