Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including await-result with all npm packages installed. Try it out:

var awaitResult = require("await-result")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

await-result v2.3.0

Error handling for async functions without try/catch blocks

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 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.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free