Detect if Value Is a Promise in Node.js and JavaScript

You may want to add different behavior for different input types when working with functions in Node.js and JavaScript. For example, if an input is a promise, you want to resolve it first before moving on with the actual processing.

This tutorial shows you how to detect whether a given value is a promise.

Node.js Series Overview

Detect if Value Is a Promise

You may heard the term “thenable” related to promises in JavaScript. This term originates from the .then() method. A promise describes a placeholder for an asynchronous computation that only returns the value to a given callback if you call .then(callback).

You can use this behavior to determine whether a given value is a promise. Because promises implement the .then() method, you can check whether it’s a function. If yes, it’s a promise!

Here’s a sample function determining if an input is a promise:

/**
 * Determine whether the given `promise` is a Promise.
 *
 * @param {*} promise
 *
 * @returns {Boolean}
 */
function isPromise(promise) {  
    return !!promise && typeof promise.then === 'function'
}

The isPromise function checks whether the promise argument exists and if yes, does it provide a .then() method. If both checks are true, you have a promise.

Using the isPromise() Function

Here are some examples showing how to use the isPromise function with different inputs. The returned value is a comment below the method call:

isPromise(new Promise(() => {}))  
// true

async function asyncFn () {  
  return 'async'
}
isPromise(asyncFn())  
// true

isPromise()  
// false

isPromise(1)  
// false

isPromise('no')  
// false

More Goodies

The isPromise function is part of the supercharge/goodies package. You can destructure the isPromise method and other goodies from the package. Well, you can copy and paste the function above to your codebase 😃

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.