Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
can i chain request in vue method?

I have a button when user click on it I will send a request and receive answer. If user click 100 times on this button I want to send 100 requests to server and each request send after previous. because I need previous response in next request.

example:

    <button @click="sendRequest">send</button>
    
    methods:{
    
    sendRequest:function(){
    
        axios.post('https:/url/store-project-item', {
            'id': this.project.id,
            "items": this.lists,
            'labels': this.labels,
            'last_update_key': this.lastUpdateKey,
            'debug': 'hYjis6kwW',
          }).then((r) => {
            if (r.data.status) {
              this.change = false
              this.lastUpdateKey = r.data.lastUpdateKey;
              this.showAlert('success')
            } else {
              if (r.data.state == "refresh") {
                this.showAlert('error')
                this.getProject()
              } else {
                this.showAlert('error')
              }
            }
          }).catch(() => {
            this.showAlert('error')
          })
        }}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I keep a higher-order function (i.e. a function that returns a function) withMaxDOP (DOP = degrees-of-parallelism) handy for this kind of thing:

const withMaxDOP = (f, maxDop) => {
  const [push, pop] = createAsyncStack();
  for (let x = 0; x < maxDop; ++x) {
    push({});
  }
  return async(...args) => {
    const token = await pop();
    try {
      return await f(...args);
    } finally {
      push(token);
    }
  };
};

The function makes use of an async stack data structure (implementation is in the attached demo), where the pop function is async and will only resolve when an item is available to be consumed. maxDop tokens are placed in the stack. Before invoking the supplied function, a token is popped from the stack, sometimes waiting if no token is immediately available. When the supplied completes, the token is returned to the stack. This has the effect of limiting concurrent calls to the supplied function to the number of tokens that are placed in the stack.

You can use the function to wrap a promise-returning (i.e. async) function and use it to limit re-entrancy into that function.

In your case, it could be used as follows:

sendRequest: withMaxDOP(async function(){ /*await axios.post...*/ }, 1)

to ensure that no call to this function ever overlaps another.

Demo:

const createAsyncStack = () => {
  const stack = [];
  const waitingConsumers = [];
  const push = (v) => {
    if (waitingConsumers.length > 0) {
      const resolver = waitingConsumers.shift();
      if (resolver) {
        resolver(v);
      }
    } else {
      stack.push(v);
    }
  };
  const pop = () => {
    if (stack.length > 0) {
      const queueItem = stack.pop();
      return typeof queueItem !== 'undefined' ?
        Promise.resolve(queueItem) :
        Promise.reject(Error('unexpected'));
    } else {
      return new Promise((resolve) => waitingConsumers.push(resolve));
    }
  };
  return [push, pop];
};
const withMaxDOP = (f, maxDop) => {
  const [push, pop] = createAsyncStack();
  for (let x = 0; x < maxDop; ++x) {
    push({});
  }
  return async(...args) => {
    const token = await pop();
    try {
      return await f(...args);
    } finally {
      push(token);
    }
  };
};
// example usage
const delay = (duration) => {
  return new Promise((resolve) => setTimeout(() => resolve(), duration));
};
async function doSomething(name) {
  console.log("starting");
  // simulate async IO
  await delay(1000);
  const ret = `hello ${name}`;
  console.log(`returning: ${ret}`);
  return ret;
}
const limitedDoSomething = withMaxDOP(doSomething, 1);
//call limitedDoSomething 5 times
const promises = [...new Array(5)].map((_, i) => limitedDoSomething(`person${i}`));
//collect the resolved values and log
Promise.all(promises).then(v => console.log(v));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!