Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda