await-to-js

raw JSON →
3.0.0 verified Fri May 01 auth: no javascript

await-to-js is a lightweight zero-dependency utility that wraps a Promise and returns an array with either an error or the resolved value, enabling a Go-like error handling pattern in async/await functions. The current stable version is 3.0.0, with a stable release cadence. It ships TypeScript definitions. Differentiators: extremely simple API, tree-shakable, no external dependencies. It is commonly used in Node.js and browser environments to avoid try-catch blocks and improve code readability when handling promise rejections.

error TypeError: to is not a function
cause Using CommonJS require without .default: const to = require('await-to-js') returns an object with a default property.
fix
Use const to = require('await-to-js').default;
error Module '"await-to-js"' has no exported member 'to'.
cause Trying to import a named export when the package only provides a default export.
fix
Change import { to } from 'await-to-js' to import to from 'await-to-js'
error Cannot find module 'await-to-js' or its corresponding type declarations.
cause TypeScript resolution issue; package may not be installed or tsconfig misconfigured.
fix
Install the package: npm install await-to-js. Ensure tsconfig.json includes 'node' in moduleResolution or set 'esModuleInterop': true.
breaking In version 2.0.0, the return type changed from [Error|null, any] to [Error|undefined, any]. Check for existing code that strictly compares null.
fix Update comparisons: if (err !== null) should become if (err !== undefined).
breaking In version 3.0.0, the package switched to ESM-only. CommonJS require() will not work without .default.
fix Use import to from 'await-to-js' or const to = require('await-to-js').default;
gotcha If the promise rejects with a non-Error value (e.g., a string), the error component will be that value, not an Error instance.
fix Ensure your promises reject with Error objects for consistent error handling.
breaking Version 1.x exported a named export instead of default. Using import to from 'await-to-js' would fail.
fix Upgrade to latest version and use default import. For old code, use import { to } from 'await-to-js'.
npm install await-to-js
yarn add await-to-js
pnpm add await-to-js

Demonstrates basic usage of await-to-js to handle a resolved promise, checking for error first.

import to from 'await-to-js';

async function fetchData() {
  const promise = Promise.resolve({ id: 1, name: 'test' });
  const [err, data] = await to(promise);
  if (err) {
    console.error('Error:', err);
    return;
  }
  console.log('Data:', data);
}

fetchData();