如何确定浏览器是否支持 Promise [英] How to determine if a Promise is supported by the browser

查看:67
本文介绍了如何确定浏览器是否支持 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道,使用 Modernizr 或其他方式,是否有办法检测浏览器中是否启用了 Promise 功能?

Does anyone know, using Modernizr or otherwise, if there is a way to detect if the Promise feature is enabled in a browser?

我有一个用于该功能的 polyfill,但只想在浏览器没有本机实现时应用它.

I have a polyfill for the functionality, but only want to apply it if the browser does not have a native implementation.

推荐答案

2016 年 12 月 11 日 - 更新:所有常绿版本的浏览器现在都支持 promise.它们可以安全使用.

Update Dec 11 - 2016: All evergreen versions of browsers now support promises. They are safe to use.

2016 年 11 月 14 日更新:Chrome、Firefox、Safari 和 IE 现在都在其开发渠道中提供了对 promise 的实验性支持.规范已经确定.我现在仍然不会依赖于实现,而是会使用一个库,但这可能会在几个月内发生变化.

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.

没有浏览器以可靠的方式原生支持 Promise.规范可能会发生变化——至少会持续几个月.我的建议是使用像 Bluebird 这样的快速承诺库.

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
}

正如其他人所建议的,只要检查是否有 Promise 对象就可以通过 if(Promise) 来完成,但我强烈建议不要这样做,因为不同的库有不同的 API创建承诺等.

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.

这篇关于如何确定浏览器是否支持 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆