Home > database >  In javascript, why doesn't await return an error when a promise catches?
In javascript, why doesn't await return an error when a promise catches?

Time:04-29

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

CodePudding user response:

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.

CodePudding user response:

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