is-promise

4.0.0 · active · verified Tue Apr 21

is-promise is a minimalist utility that determines if an object adheres to the Promises/A+ specification by duck-typing, specifically checking for the presence and function type of a `then` method. The package is currently at version 4.0.0, which primarily introduced a breaking change for TypeScript users regarding `PromiseLike` inference. While it doesn't follow a strict, rapid release cadence, major versions address significant compatibility updates, particularly concerning module resolution in Node.js environments and TypeScript definitions. Its key differentiator is its small footprint and focused API, providing a reliable and agnostic way to identify promise-like objects, useful in contexts where various promise implementations or thenables might be encountered, without relying on a global `Promise` constructor.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `isPromise` to check various values, including actual promises, custom thenables, and non-promise types, and correctly handle their resolution.

import isPromise from 'is-promise';

async function processValue(value: unknown): Promise<string> {
  if (isPromise(value)) {
    console.log('Value is a promise, awaiting...');
    const result = await value;
    return `Resolved from promise: ${result}`;
  } else if (typeof value === 'string') {
    console.log('Value is a string.');
    return `Direct string: ${value}`;
  } else if (typeof value === 'object' && value !== null && 'then' in value && typeof (value as any).then === 'function') {
    console.log('Value is promise-like (has a then method), awaiting...');
    const result = await (value as PromiseLike<any>);
    return `Resolved from promise-like: ${result}`;
  } else {
    console.log('Value is neither a promise nor a string.');
    return 'Unknown value type.';
  }
}

(async () => {
  console.log(await processValue(Promise.resolve('Hello from a real promise')));
  console.log(await processValue({ then: (resolve: (arg0: string) => void) => setTimeout(() => resolve('Hello from a custom thenable'), 100) }));
  console.log(await processValue('Hello from a string'));
  console.log(await processValue(null));
  console.log(await processValue({ then: true })); // 'then' is not a function, so not a promise.
})();

view raw JSON →