Last active
April 18, 2018 19:32
-
-
Save vigneshshanmugam/5ab3f3220344d2e01118267b8b5e0680 to your computer and use it in GitHub Desktop.
Test if a given function is promise
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
// From graphql-js, https://github.com/graphql/graphql-js/blob/499a75939f70c4863d44149371d6a99d57ff7c35/src/jsutils/isPromise.js#L18 | |
function isPromiseWithBoxing(value) { | |
return Boolean(value && typeof value.then === "function"); | |
} | |
// Tailor source - https://github.com/zalando/tailor/blob/0d930d30d6ea3936985ecf3714a3d93fa755b628/src/pipe.js#L53 | |
function isPromiseWithoutBoxing(value) { | |
return ( | |
value != null && | |
typeof value === "object" && | |
typeof value.then === "function" | |
); | |
} | |
function isPromiseWithoutBoxing2(value) { | |
return value && typeof value.then === "function"; | |
} | |
// From bluebird source - https://github.com/petkaantonov/bluebird/blob/3746b7eca90dd8b11af73db5d30cf46d7dd90f9b/test/mocha/helpers/bluebird0_7_0.js#L674 | |
function isPromiseBluebird(obj) { | |
if (typeof obj !== "object") return false; | |
return obj instanceof Promise; | |
} | |
const dumbPromise1 = Promise.resolve(1); | |
const dumbPromise2 = Promise.resolve(2); | |
const dumbPromise3 = Promise.resolve(3); | |
const dumbPromise4 = Promise.resolve(4); | |
console.time("isPromiseWithBoxing"); | |
for (let i = 0; i < 1e7; i++) { | |
isPromiseWithBoxing(dumbPromise1); | |
} | |
console.timeEnd("isPromiseWithBoxing"); | |
console.time("isPromiseWithoutBoxing"); | |
for (let i = 0; i < 1e7; i++) { | |
isPromiseWithoutBoxing(dumbPromise2); | |
} | |
console.timeEnd("isPromiseWithoutBoxing"); | |
console.time("isPromiseWithoutBoxing2"); | |
for (let i = 0; i < 1e7; i++) { | |
isPromiseWithoutBoxing2(dumbPromise3); | |
} | |
console.timeEnd("isPromiseWithoutBoxing2"); | |
console.time("isPromiseBluebird"); | |
for (let i = 0; i < 1e7; i++) { | |
isPromiseBluebird(dumbPromise4); | |
} | |
console.timeEnd("isPromiseBluebird"); |
Author
vigneshshanmugam
commented
Apr 18, 2018
When i change it to rejection
const dumbPromise1 = Promise.reject(1).catch(_ => {});
const dumbPromise2 = Promise.reject(2).catch(_ => {});
const dumbPromise3 = Promise.reject(3).catch(_ => {});
const dumbPromise4 = Promise.reject(4).catch(_ => {});
Results
isPromiseWithBoxing: 19.332ms
isPromiseWithoutBoxing: 14.083ms
isPromiseWithoutBoxing2: 17.172ms
isPromiseBluebird: 38.480ms
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment