Socket
Book a DemoInstallSign in
Socket

handle-async-await

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

handle-async-await

Graceful Error Handling with Async Await

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

Handle Async Await

The Anti-Pattern

You want to use an async function with an error handler. So you use a try-catch block. But now you cannot assign the return value of this async function to a constant declared outside the try-catch because of the block scope. And so you are forced to use a variable in lieu of a constant!

let x; // not const
try {
  x = await myAsyncFn()
}
catch (error) {
  handleError(error);
}

You can always place the try-catch block in a function but this gets tedious and breaks the flow of program logic:

function myAsyncFnWithErrorHandler() {
  try {
    return await myAsyncFn();
  }
  catch (error) {
    handleError(error);
  }
}

const x = await myAsyncFnWithErrorHandler();

Handle Async Await makes it easier to use async functions with error handling.

Installation

Install Handle Async Await with your favourite package manager:

<npm|pnpm|yarn> add handle-async-await

Usage

Error Handler

In the most general form, users can supply their own error handling function.

import handleAA from 'handle-async-await';

const x = await handleAA(myAsyncFn(), handleError);

Error String

If you just wish to augment the error message and throw an error, supply only the string to be appended to the error message as the second argument.

import handleAA from 'handle-async-await';

const x = await handleAA(myAsyncFn(), 'A custom error message');

A space is added when the error message does not end with a whitespace. Bring your own punctuation!

Copyright © 2021, Rahul Gupta.

Handle Async Await is distributed under the terms of the Mozilla Public License, v. 2.0.

Keywords

promise

FAQs

Package last updated on 01 Apr 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.