如何支持 Internet Explorer 11 中的承诺?

How to support promises in Internet Explorer 11?

我有一个简单的代码,可以在除 Internet Explorer 11 之外的所有浏览器上完美运行。我怎样才能让它在所有浏览器上运行?

Codepen

'use strict';

let promise = new Promise((resolve, reject) => {

  setTimeout(() => {
    resolve("result");
  }, 1000);
});

promise
  .then(
    result => {
      alert("Fulfilled: " + result);
    },
    error => {
      alert("Rejected: " + error);
    }
  );

如果你想让这种类型的代码在 IE11 中 运行(它根本不支持大部分 ES6),那么你需要获得一个第 3 方承诺库(比如 Bluebird) ,包含该库并更改您的编码以使用 ES5 编码结构(没有箭头功能,没有 let,等等...)这样您就可以在旧浏览器支持的范围内生活。

或者,您可以使用转译器(如 Babel)将 ES6 代码转换为可在旧版浏览器中运行的 ES5 代码。

这是使用 Bluebird promise 库以 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>

您可以尝试使用 Polyfill。以下 Polyfill 于 2019 年发布,对我有用。它将 Promise 函数分配给 window 对象。

像这样使用:window.Promise https://www.npmjs.com/package/promise-polyfill

如果您想了解有关 Polyfill 的更多信息,请查看以下 MDN 网络文档 https://developer.mozilla.org/en-US/docs/Glossary/Polyfill