Skip to content

Instantly share code, notes, and snippets.

@reggi
Last active June 17, 2020 22:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save reggi/a1da4d0ea4f1320fa15405fb86358cff to your computer and use it in GitHub Desktop.
Save reggi/a1da4d0ea4f1320fa15405fb86358cff to your computer and use it in GitHub Desktop.
const assert = require('assert')
const BLUEBIRD = require('bluebird')

const nameAsync1 = async (name) => name
const nameAsync2 = (name) => Promise.resolve(name)
const nameAsync3 = (name) => BLUEBIRD.resolve(name)
const nameSync = (name) => name

const isPromise1 = (value) => Promise.resolve(value) === value
const isPromise2 = (value) => BLUEBIRD.resolve(value) === value

assert(isPromise1(nameAsync1('thomas')) === true, 'async function is native promise')
assert(isPromise1(nameAsync2('thomas')) === true, 'native promise resolved is native promise')
assert(isPromise1(nameAsync3('thomas')) === true, 'bluebird resolved promise is native promise')

assert(isPromise2(nameAsync1('thomas')) === true, 'async function is bluebird promise')
assert(isPromise2(nameAsync2('thomas')) === true, 'native promise resolved is bluebird promise')
assert(isPromise2(nameAsync3('thomas')) === true, 'bluebird resolved promise is bluebird promise')

// console.log(isPromise1(nameSync('thomas')))
// console.log(isPromise2(nameSync('thomas')))

// console.log(isPromise1({ then: () => {} }))
// console.log(isPromise2({ then: () => {} }))

screen shot 2018-03-07 at 12 01 28 am

@onury
Copy link

onury commented Sep 12, 2018

This doesn't make sense to me. You're executing the function to check if it's a promise.
You can simply do Promise.resolve(fn()).then(...) in your code; to ensure it's a promise.
Why would you ever need this?

@kyeotic
Copy link

kyeotic commented Oct 8, 2019

@onury Sometimes you need to do different things for promises. You also can do things differently when things are not promises: like synchronously inspect their value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment