Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!