await-result
Error handling for async functions without try/catch blocks
Motivation
I find the way that errors are handled in Go to be elegant, and wanted to make something to emulate that behavior in JavaScript while also taking advantage of the new async / await feature available in newer versions of Node.js (7.6+).
Installation
For use with Node.js 7.6 or later, unless you're using a transpiler such as Babel.
$ yarn add await-result
Or, with npm
:
$ npm install --save await-result
Usage
There are a few ways you can use this helper function:
Get error and return value
You'll usually just call the function with only one argument - the function that returns a Promise:
const err data = await ;
You can then do something with the error and return value without having to worry about try-catch blocks.
Process error first
Similarly, you can get the error and return value, but process the error first; this is very useful in larger projects where you might want to operate on the error in a consistent manner:
const processedErr data = await ;
Example
; { const err num = await ; if err throw err; return num;} ;
Contributing
See CONTRIBUTING.md.
License
MIT License. See LICENSE for details.