2.3.2 • Published 5 years ago

await-result v2.3.2

Weekly downloads
94
License
MIT
Repository
github
Last release
5 years ago

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.

2.3.2

5 years ago

2.3.1

5 years ago

2.3.0

6 years ago

2.2.1

6 years ago

2.2.0

7 years ago

2.1.0

7 years ago

2.0.0

7 years ago

1.2.0

7 years ago

1.1.0

8 years ago

1.0.7

8 years ago

1.0.6

8 years ago

1.0.5

8 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago