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

107
Vistas
async/await access previous result and pass it to next operation

If my function uses two independent async operations, then an unreachable backend between the first and second operation would result in a (stored) and b (not stored).

try {
  const a = await createA();
  // error: backend not available
  const b = await createB();
}

I could use await Promise.all(), to wait until all promises are resolved, so either both are stored or none are stored.

await Promise.all([createA(), createB()]);

But how to solve this situation, if my second async operation depends on the result of the first one.

try {
  const a = await createA();
  // error: backend not available
  const b = await createB({ _id: a._id });
}

Is there any way to handle this with using async and await and not chained .then() statements?

Edit: I expect that a and b will be created or none of both. Both operations a and b saves documents via mongoose driver to a mongodb database.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You want to create a promisePipe instead using reduce. With reduce you can use the output of the previous operation as input for the next operation.

For example:

const myPromise = async n => {
    return Promise.resolve(1 * n)
}

const myPromise2 = async n => {
    return Promise.resolve(2 * n)
}

const promiseReduce = async (prevPromise, currPromise) => {
  const prevResult = await prevPromise;
  return currPromise(prevResult).catch(err => {
    throw err // throw a internal error server here
  });
}
    
const promisePipe = (...fns) => {
    return fns.reduce(promiseReduce, Promise.resolve(1))
}

promisePipe(myPromise, myPromise2).then(e => { console.log(e)})

about 4 years ago · Juan Pablo Isaza Denunciar

0

if the second function depends upon the first result then you can use the below snippet:

try {
     const a = await createA();
       // null and if id is exists than call createB
        if (a && a.id) {
            const b = await createB();
        }
}
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