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

147
Visualizações
Preventing the saving of data if one fails on Promise.all - VueJS

I have two forms with data that needs to be saved using two separate post APIs. I am using Promise.all() to save all the data from these two forms at once and its working as it should. The code is as follows:

saveAll() {
        Promise.all([
            this.$axios.post('v1/dummy-api/one',
              this.saveFormOne()
            ),
            this.$axios.post('v1/dummy-api/two',
              this.saveFormTwo()
            )
          ])
          .then(() => {
            this.success = 'Added Successfully.';
          })
          .catch(error => {
            this.error = 'Error.';
          })
      },

The issue am trying to solve is I need to check if any of those two request fails and if it does then prevent/cancel the saving of the other one (which succeed) until all of them succeed. I've tried try/catch with no luck.

Any help will greatly appreciated!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to use Axios AbortController (https://axios-http.com/docs/cancellation). Be wary though that cancelling a request might not necessarily guarantee that the POST has not already been properly executed. If you must not call the other endpoint if one fails, the easiest way would be to chain them and call one after another.

Anyway, a way to achieve this is shown underneath. Note that I needed to modify it a bit in order for it to be executable inside stackoverflow answer. You'd get a general idea from it, though.

function saveAll() {
    const cancel = new AbortController();
    Promise.all([
            axios.get('https://test-stackoverflow.free.beeceptor.com', {}, {
                signal: cancel.signal
            }).catch((e) => {
                cancel.abort();
                throw e;
            }),
            axios.get('https://thiswillfail.com/fail', {}, {
                signal: cancel.signal
            }).catch((e) => {
                console.log('second request has failed')
                cancel.abort();
                throw e;
            })
        ])
        .then(() => {
            alert('Added Successfully.');
        })
        .catch(error => {
            alert('Error.');
        })
}
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<button onclick="saveAll()">save all</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

async saveAll() { 
 const resp1 = await this.$axios.post('v1/dummy-api/one', this.saveFormOne())
 const resp2 = await this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
}

I don't know if this can be solved

about 4 years ago · Juan Pablo Isaza Relatório

0

Promise.all() is not what you need if you need to manage these API calls. You can do somethin similar to what 王超华 suggested, but with additional try/catch

async function saveAll() { 
  let first;
  try {
    first = await this.$axios.post('v1/dummy-api/one', this.saveFormOne())
  } catch (e) {
    console.log('first failed')
    return
  }
  console.log('first', first)

  const second = await this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
  console.log('second', second)
}

Or if you want to use Promises

saveAll() {
      this.$axios.post('v1/dummy-api/one', this.saveFormOne())
      .then(() => this.$axios.post('v1/dummy-api/two', this.saveFormTwo())
      .then(() => this.success = 'Added Successfully.')
      .catch(error => this.error = 'Error.')
  }
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