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

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

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 Denunciar

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 Denunciar

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 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