Javascript 如何使承诺在 IE11 中工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36016327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make promises work in IE11
提问by Billy Logan
I have a simple code that runs perfectly on every browser except for the Internet Explorer 11. How can I make it work on all browsers?
我有一个简单的代码,可以在除 Internet Explorer 11 之外的所有浏览器上完美运行。如何使其在所有浏览器上运行?
Thanks in advance.
提前致谢。
'use strict';
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result");
}, 1000);
});
promise
.then(
result => {
alert("Fulfilled: " + result);
},
error => {
alert("Rejected: " + error);
}
);
回答by jfriend00
If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let
, etc...) so you can live within the limits of what older browsers support.
如果您希望这种类型的代码在 IE11(它根本不支持大部分 ES6)中运行,那么您需要获得一个 3rd 方承诺库(如Bluebird),包含该库并更改您的编码以使用 ES5 编码结构(没有箭头功能,没有let
,等等...)所以你可以生活在旧浏览器支持的范围内。
Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.
或者,您可以使用转译器(如Babel)将您的 ES6 代码转换为适用于旧浏览器的 ES5 代码。
Here's a version of your code written in ES5 syntax with the Bluebird promise library:
这是使用 Bluebird 承诺库以 ES5 语法编写的代码版本:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script>
'use strict';
var promise = new Promise(function(resolve) {
setTimeout(function() {
resolve("result");
}, 1000);
});
promise.then(function(result) {
alert("Fulfilled: " + result);
}, function(error) {
alert("Rejected: " + error);
});
</script>
回答by ScottyG
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
您可以尝试使用 Polyfill。以下 Polyfill 于 2019 年发布,对我有用。它将 Promise 函数分配给 window 对象。
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
使用如下:https: window.Promise
//www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
如果您想了解有关 Polyfill 的更多信息,请查看以下 MDN 网络文档 https://developer.mozilla.org/en-US/docs/Glossary/Polyfill