await-result
TypeScript icon, indicating that this package has built-in type declarations

2.3.2 • Public • Published

await-result

Error handling for async functions without try/catch blocks


npm version build status code coverage

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 result(func());

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 result(func(), customErrorHandler);

Example

import result from 'await-result';
 
async function getNumUsers() {
    const [ err, num ] = await result(database.userCount(), customErrorHandler);
 
    if (err) {
        throw err;
    }
 
    return num;
}
 
getNumUsers().then((count) => {
    console.log(`Total number of users: ${count}`);
}).catch((err) => {
    console.log(err);
});

Contributing

See CONTRIBUTING.md.

License

MIT License. See LICENSE for details.

Package Sidebar

Install

npm i await-result

Weekly Downloads

127

Version

2.3.2

License

MIT

Unpacked Size

79.5 kB

Total Files

13

Last publish

Collaborators

  • tylucaskelley