Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: fix promise check to accept any spec conform object (#1424)
An instanceof check only accept promises which are created using the `Promise` constructor. But there are other libraries which their own contructors. These promises should also work as long as they adhere to the spec.
- Loading branch information
Showing
2 changed files
with
35 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
module.exports = function isPromise (maybePromise) { | ||
return maybePromise instanceof Promise | ||
return !!maybePromise && !!maybePromise.then && (typeof maybePromise.then === 'function') | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
'use strict' | ||
/* global describe, it */ | ||
|
||
const { expect } = require('chai') | ||
const isPromise = require('../lib/is-promise') | ||
|
||
describe('isPromise', () => { | ||
it('returns `false` on non promise value', () => { | ||
expect(isPromise('hello there.')).to.be.equal(false) | ||
}) | ||
|
||
it('returns `true` on es6 promise', () => { | ||
const esPromise = new Promise(() => {}) | ||
expect(isPromise(esPromise)).to.be.equal(true) | ||
}) | ||
|
||
it('returns `true` on some other thenable', () => { | ||
const thenable = { then: () => {} } | ||
expect(isPromise(thenable)).to.be.equal(true) | ||
}) | ||
|
||
it('returns `false` if some falsy value is passed', () => { | ||
expect(isPromise(null)).to.be.equal(false) | ||
}) | ||
|
||
it('returns `false` if passed object has no `then` property', () => { | ||
expect(isPromise({})).to.be.equal(false) | ||
}) | ||
|
||
it('returns `false` if `then` is not a function', () => { | ||
const obj = { then: 4711 } | ||
expect(isPromise(obj)).to.be.equal(false) | ||
}) | ||
}) |