Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda