Unified Async/Sync Function Execution

4.0.6 · active · verified Sun Apr 19

run-async is a utility method designed to normalize the execution of functions that can operate synchronously, asynchronously via a `this.async()` callback, or by returning a Promise. This library is particularly useful for authors of middleware or plugins that need to accept user-provided functions with varying asynchronous patterns, ensuring a consistent execution flow. The current stable version is 4.0.6, and the project demonstrates an active maintenance cadence, addressing dependency issues and enhancing functionality across major versions. A key differentiator is its ability to abstract away the underlying async mechanism, providing a single interface, and its current status as a dependency-free package since version 2.4.1, which improves reliability and reduces supply chain risks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `runAsync` to execute functions that use `this.async()`, return a Promise, or return a synchronous value. Also includes an example of `runAsync.cb` for Node.js callback-style functions.

import { runAsync } from 'run-async';

// A helper to demonstrate how runAsync normalizes different function types
const printAfter = async (func: Function) => {
  const cb = (err: Error | null, returnValue: unknown) => {
    if (err) {
      console.error('Error:', err);
      return;
    }
    console.log(returnValue);
  };

  // Execute the function using runAsync, passing a callback
  // runAsync returns a function that takes arguments for func
  try {
    const result = await runAsync(func, cb)();
    // If func returns a Promise, runAsync resolves it. The callback also fires.
    // We'll catch the potential Promise resolution here.
    // The callback provided to runAsync will still be called.
  } catch (error) {
    console.error('Caught an error from runAsync execution:', error);
  }
};

console.log('--- Using this.async ---');
printAfter(function (this: any) {
  const done = this.async();
  setTimeout(() => {
    done(null, 'done running with callback');
  }, 10);
});

console.log('\n--- Returning a Promise ---');
printAfter(function () {
  return new Promise(resolve => {
    setTimeout(() => resolve('done running with promises'), 5);
  });
});

console.log('\n--- Synchronous function ---');
printAfter(function () {
  return 'done running sync function';
});

// Example using runAsync.cb for Node.js callback style
console.log('\n--- Using runAsync.cb (Node.js callback style) ---');
runAsync.cb(
  (a: number, b: number, cb: (err: Error | null, result: number) => void) => {
    setTimeout(() => cb(null, a + b), 20);
  },
  (err: Error | null, result: number) => {
    if (err) console.error('Error with runAsync.cb:', err);
    else console.log(`runAsync.cb result: ${result}`);
  }
)(5, 7);

view raw JSON →