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

165
Vistas
Returning promise from async function

Can promise to be returned like below? Does the catch block return a promise or a normal Error?

async function beforeProcessing(ctx) {
  try {
      let res = await validateList(ctx)
      return new Promise((resolve, reject) => {
          if (res && res.length > 0) {
              const customErr = new Error(`missing for ${res} types`);
              customErr.statusCode = 422;
              reject(customErr);
          }
          else {
              resolve();
          }
      })
  } catch (error) {
      return new Error(error);
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, but there's no reason to. async functions always return promises. Just handle that logic inline, and throw customErr to reject the function's promise:

async function beforeProcessing(ctx) {
    let res;
    try {
        res = await validateList(ctx)
    } catch (error) {
        return new Error(error); // *** This is highly suspect
    }
    if (res && res.length > 0) {
        const customErr = new Error(`missing for ${res} types`);
        customErr.statusCode = 422;
        throw customErr;
    }
}

But as I mentioned in a comment above, returning an error object is highly suspect, it fulfills the promise with the error rather than rejecting the promise. Just let the error propagate to the caller (which will reject the async function's promise):

async function beforeProcessing(ctx) {
    let res = await validateList(ctx)
    if (res && res.length > 0) {
        const customErr = new Error(`missing for ${res} types`);
        customErr.statusCode = 422;
        throw customErr;
    }
}

Also, that if condition looks odd vs. the error message. The error message makes it look like the condition should be <= 0, not > 0, but of course I could be inferring incorrectly there.

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