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

166
Visualizações
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 Respostas
Responde à pergunta

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