npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

am

v1.1.0

Published

A simple and light way to run a main function asynchronously

Downloads

204

Readme

A simple, secure light and unified way to run a top level async function addressing some common edge cases.

Its main use case is for creating Node CLIs.

Do I really need this? No, if you are asking. Yes, if a simple IIFE doesn't do the job and you find yourself dealing with unexpected bugs and copy/pasted workarounds.

  • 0️⃣ No dependency
  • 🐭 Minimal and readable code
  • ⚠ On throw, sets the process exit code to a non-zero value (1)
  • Listens to unhandledRejection error and prints the stack trace and the name of the faulty function and sets the process exit code to a non-zero value (2)
  • 🏳 Works with async functions, native or custom promises
  • 💌 Passes arguments as parameters to the main function
  • 💊 Supports custom error handlers

Install

npm i am

(no pun intended!) 😎

Why?

We ♥ async functions but what if the main logic of your application runs asynchronously? Top level await is not supported because of complications.

Most of the times a naïve Immediately Invoked Function Expression does the job:

(async function main() {
    // my async-await logic
})()

That does not look elegant but it works. Kinda! If main() throws, you're dealing with an Unhandled Promise Rejection. You get this:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Despite that, the process exit code remains 0 which means if you're chaining your script in a bash script (using && for example), the rest of the chain will continue. am grew to handle these kinds of edge cases in a standard way. It stands for async main and works like this:

const am = require('am')

am(async function main() {
    // my async-await logic
})

Or even:

const am = require('am')

async function main() {
    // my async-await logic
}

am(main)

As a bonus it passes the node CLI parameters to main. So if you call your file like:

$ node my-script.js apple orange

Then your main() function gets them as two arguments:

// my-script.js
const am = require('am')

am(async function main(foo, bar) {
    console.log(foo) // "apple"
    console.log(bar) // "orange"
})

If you prefer, you can directly pass those CLI params to something more sophisticated like minimist:

// my-script.js
const am = require('am')
const minimist = require('minimist')

am(async function main(...cliArgs) {
    const argv = minimist(cliArgs)
    console.dir(argv) // { _: ["apple", "orange" ] }
})

API

am(main, errorHandler?): void

  • main is an async or sync (traditional) function. If there's an error the errorHandler will be called, otherwise a default error handler will be used which prints the error and sets the process.exitCode to 1.
  • The main function will get the CLI arguments as its parameters in the order they were typed by the user.
  • When you first call am, it will listen to unhandledRejection event and prints the error message referring to the failed promise and sets the process.exitCode to 2. The default or provided errorHandler will not be called (that way you can call am() as many times as needed)
  • errorHandler an optional async or sync (traditional) function that'll be called if the main() function throws. It takes the error as its argument. Even if you provide your custom error handler, we still set the process.exitCode to 1 if you forget to set it to a non-zero value. Also, if your custom errorHandler throws for whatever reason, am will use its default error handler.

The am() function returns a promise which always resolves to the value returned from main().


Made in Sweden by @alexewerlof