How to determine if a Promise is supported by the browser

倾然丶 夕夏残阳落幕 提交于 2019-11-29 22:57:58

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.

Not so fast.

This throws when "Promise" is undefined:

if (Promise)
  // do code

This never throws:

if (window.Promise)
  // do code

and yes the window object can be relied upon in a browser environment.

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.

JSFiddle

To create a 'supported' flag without carrying around an object reference:

var canPromise = !! window.Promise;

Here is a page listing browser and runtime support for Promise: https://kangax.github.io/compat-table/es6/

if (Promise) {
   alert("Promise is supported!");
} else {
   alert("Promise is not supported!");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!