Explain Codes LogoExplain Codes Logo

How to check if an object is a Promise?

javascript
promises
javascript-features
best-practices
Alex KataevbyAlex Kataev·Sep 13, 2024
TLDR

Here's a concise way to identify if an object is a Promise. We're relying on the presence of a then method (a classic indicator) or the instanceof keyword:

let isPromise = obj instanceof Promise || !!(obj && typeof obj.then === 'function'); // I'm Promise-ive! 😉

This mnemonic covers both structural and inheritance-based tests in one fell swoop!

Promise-proof your checks with optional chaining

In the brave new world where optional chaining has your back, you can fortify against unexpected null or undefined values:

let isPromise = obj instanceof Promise || typeof obj?.then === 'function'; // Safe navigation - no Titanic! 🚢

It's like adding training wheels to your object checks to prevent crashes! 🚴‍♀️

Non-standard Promises: "Thenables"

In situations where you're wrestling with non-native or shimmed Promises, look out for "thenable" objects:

let isThenable = obj != null && typeof obj === 'object' && typeof obj.then === 'function'; // If it walks like a duck and quacks like a duck...

This approach recognizes anything with a then method. Useful when dealing with the Promises/A+ specification in the wild!

The shady side of Promise.resolve

Beware rookie mistakes when using Promise.resolve:

  • Promise.resolve can be deceptive. When fed a promise-like object, it does not return the original object but births a brand-new Promise.
  • In case of constructor-created promises, Promise.resolve might play a swap game, not returning the same instance.

Mind your steps, explorers!

Tricky situations and pro tips

  • instanceof: Not always reliable for Promises from parallel universes (other realms like iframes etc.).
  • Cross realms: Promises from another realm or window might flunk this test as they use a different Promise constructor.
  • Assorted libraries: Promises from custom libraries might not pass this test. They like to march to their own drum, you know!

Why algorithmic checks rule

  • Compatibility: Brings different Promise implementations under one umbrella.
  • Uniformity: Abides by the general traits of Promises rather than strict structure.

Top use-cases for developers

Code systematically to handle Promises from all sorts of origins. This is especially relevant if you're building libraries or solutions aiming at multiple JavaScript environments.