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

159
Views
¿Puedo encadenar una solicitud en el método vue?

Tengo un botón cuando el usuario hace clic en él. Enviaré una solicitud y recibiré una respuesta. Si el usuario hace clic 100 veces en este botón, quiero enviar 100 solicitudes al servidor y cada solicitud se envía después de la anterior. porque necesito una respuesta previa en la próxima solicitud.

ejemplo:

 <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

Mantengo una función de orden superior (es decir, una función que devuelve una función) withMaxDOP (DOP = grados de paralelismo) útil para este tipo de cosas:

 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); } }; };

La función utiliza una estructura de datos de pila asíncrona (la implementación se encuentra en la demostración adjunta), donde la función pop es async y solo se resolverá cuando un artículo esté disponible para ser consumido. Los tokens maxDop se colocan en la pila. Antes de invocar la función suministrada, se extrae un token de la pila, a veces esperando si no hay ningún token disponible de inmediato. Cuando se completa el suministro, el token se devuelve a la pila. Esto tiene el efecto de limitar las llamadas simultáneas a la función suministrada al número de tokens que se colocan en la pila.

Puede usar la función para envolver una función de devolución de promesa (es decir, async ) y usarla para limitar el reingreso a esa función.

En su caso, podría usarse de la siguiente manera:

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

para garantizar que ninguna llamada a esta función se superponga con otra.

Manifestación:

 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!