How to determine if a Promise is supported by the browser
Solution 1
Update Dec 11 - 2016: All evergreen versions of browsers now support promises. They are safe to use.
Update Nov 14 - 2016: Chrome, Firefox, Safari and IE all now have experimental support for promises in their dev channels. The specification has settled. I would still not rely on the implementation just yet and would use a library but this might change in a few months.
No browsers support promises natively in a reliable way. The specification might change - at least for a few more months. My suggestion is use a fast promise library like Bluebird.
If you want to check if native promises are enabled - you can do :
if(typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1){
//here
}
As others suggested, just checking if there is a Promise
object can be done by if(Promise)
but I strongly suggest against it since different libraries have different APIs for creation of promises etc.
Solution 2
Not so fast.
This throws when "Promise" is undefined:
if (Promise)
// do code
This never throws:
if (window.Promise)
// do code
if (typeof Promise !== 'undefined')
// do code
and yes the window object can be relied upon in a browser environment.
Solution 3
To create a 'supported' flag without carrying around an object reference:
var canPromise = !! window.Promise;
Solution 4
You could try to create one in a try/catch
block:
var promiseSupport = false;
try {
var promise = new Promise(function (x, y) {});
promiseSupport = true;
} catch (e) {}
Check promiseSupport
to see whether or not it fails.
user2836501
Updated on July 30, 2021Comments
-
user2836501 almost 3 years
Does anyone know, using Modernizr or otherwise, if there is a way to detect if the Promise feature is enabled in a browser?
I have a polyfill for the functionality, but only want to apply it if the browser does not have a native implementation.
-
Andrew Prock over 10 yearsShouldn't that be
typeof Promise !== "undefined"
, sincetypeof
returns a string? -
Benjamin Gruenbaum over 10 years@PaulRoub yeah, it started as
Promise !== undefined
but I realized the identifier might not be declared. -
Bailey Parker about 9 yearsThis is particularly useful if you want to know if the
Promise
you're working with is native or a polyfill. Unfortunately, many polyfills (including the one used by Traceur) do not set a flag to indicate that they aren't native. -
Benjamin Gruenbaum about 9 years@PhpMyCoder why would you care though?
-
Bailey Parker about 9 yearsNative Promises (well native
Promise.all()
) + Traceur generators are currently broken: github.com/google/traceur-compiler/issues/1955 -
Benjamin Gruenbaum over 6 years
Object.defineProperty(window, 'Promise', { get() { throw Error(); }});
-
Floris over 5 yearsWhat would be the reverse of this?
===
undefined and=== -1
?