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

354
Views
In javascript, why doesn't await return an error when a promise catches?

I like async/await but I don't understand why we have to wrap our await in a try/catch block to catch errors. Why not make it so await returns some type of standardized error object and then we test for that?

Then we could do something like:

let results = await somePromise();
results?.err ? doSomething() : handleErr()
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The point of async/await is to allow asynchronous/promise-based code to be written in a manner more similar to synchronous code. Synchronous code uses try/catch to handle exceptions, so it by the principal of least surprise, await should too.

about 4 years ago · Juan Pablo Isaza Report

0

Error handling is up to the author. If you don't control some code that throws, and you want it to not throw, wrap it with something that catches but doesn't throw. In your own code, you should feel free to return error objects rather than throw.

Just be aware that others have come to expect throw/catch as a convention.

// this one throws errors 
import fnNotControlledByMe from 'external_lib'  

// use this one as a wrapper, and don't throw
// this and any other function you write can opt not to throw
async function fnControlledByMe() {
  try {
    let results = fnNotControlledByMe();
    return results;
  } catch (err) {
    return { err };
  }
}

async function opFunction() {
  let results = await fnControlledByMe();
  results?.err ? doSomething() : handleErr()
}
about 4 years ago · Juan Pablo Isaza Report

0

Why not make it so await returns some type of standardized error object and then we test for that?

Because that assumes you always want to test for the error. In many (most!) cases you don't, you want to let the exception propagate. This leads to a lot boilerplate code (like the node callback pattern with error parameters), ignored errors by ignorant (unaware) programmers, and refactoring hazards.

As @SeanSutherland pointed out in his answer, this also makes asynchronous error handling symmetric to synchronous error handling, with the same expectations.

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!