简体   繁体   中英

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

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.

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()
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM