adonisjs / rfcs

💬 Sharing big changes with community to add them to the AdonisJs eco-system
52 stars 6 forks source link

Go-like shortcut for try, await, catch #7

Closed assertchris closed 6 years ago

assertchris commented 6 years ago

Brief history

async/await is awesome, and I much prefer it to working with "raw" promises or callbacks. The trouble is that promise.catch now needs to be try { await ... } catch (e) { ... } in order to be handled properly. Other languages have designed around this problem. In particular, Go has syntax resembling const [ error, result ] = await throwableOp() (this isn't Go syntax, obviously). This allows faster inspection of error states with a preference for early-exit.

What problem does it solve?

If we brought this convention to AdonisJS code, it would significantly reduce the complexity and verbosity of custom try/catch code. The convention would be to check for error states (where a global exception handler wouldn't work) and exit the scope early, instead of exiting the scope inside a catch block, after all the other logic.

Proposal

Add a tryAwait method (could definitely be named better) and use it everywhere a global exception handler isn't used but an error state is expected.

Example:

const tryAwait = async function(promise) {
  let error = undefined;
  let result = undefined;

  try {
    result = await promise;
  } catch (e) {
    error = e;
  }

  return [error, result];
};

// ...later

const [ error, customer ]  = await Customer.find(13);

if (error) {
  // exit early
}

// do something with customer

Relevant links

https://twitter.com/assertchris/status/1025036508946939904

Are you willing to work on it?

You bet your butt!

thetutlage commented 6 years ago

I believe, it will more of 10lines of utils, which can be added by anyone or shared as a recipe too.