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

114
Vistas
How to push failed promises to separate array?

I am looping through ids that sends it to an async function and I want to return both success and failed data, right now I am only returning success data

    const successContractSignature: LpContractSla[] = [];

for (const id of lpContractSlaIds) {
  const data = await createLpSignature(context, id);
  if (data) {
    successContractSignature.push(data);
  }
}

return successContractSignature;

If the createLpSignature throws error, do i need a try catch here? but wouldnt that exit the loop? How can I push failed data to separate array without breaking the loop?

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

0

Unless there's a specific reason to avoid the call in parallel, it's always a good practice to avoid to start async calls in a for loop with await, since you are going to wait for each promise to resolve (or reject ) before executing the next one. This is a better pattern which lets you also get all the results of the promises, either they resolved or rejected:

const successContractSignature: LpContractSla[] = await Promise.allSettled(lpContractSlaIds.map((id: string) => createLpSignature(context,id)))

return successContractSignature;

But if for some particular reason you need to make these calls in a sequence and not in parallel, you can wrap the single call in a try catch block ,that won't exit the loop:

for (const id of lpContractSlaIds) {
let data;
try {
  data = await createLpSignature(context, id);
} catch(e) {
  data = e
}
  if (data) {
    successContractSignature.push(data);
  }
}

You can test it in this example:

const service = (id) =>
  new Promise((res, rej) =>
    setTimeout(
      () => (id %2 === 0 ? res("ID: "+id) : rej('Error ID : '+id)),
      1000
    )
  );

const ids = [1,2,3,4,5]

const testParallelService = async () => {
  try {
  const data = await Promise.allSettled(ids.map(id => service(id)))
  return data.map(o => `${o.status}: ${o.reason ?? o.value}`)
  } catch(e) {
    console.log(e)
  }
}  
testParallelService().then(data => console.log("Parallel data: ", data))


const testSequentialService = async () => {
  const res = [];
  for (const id of ids) {
    let data;
    try {
      data = await service(id);
    } catch (e) {
      data = e;
    }
    if (data) {
      res.push(data);
    }
  }
  return res;
};

testSequentialService().then((data) => console.log('Sequential Data: ', data));

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