Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support promises in Internet Explorer 11

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?

Codepen

'use strict';  let promise = new Promise((resolve, reject) => {    setTimeout(() => {     resolve("result");   }, 1000); });  promise   .then(     result => {       alert("Fulfilled: " + result);     },     error => {       alert("Rejected: " + error);     }   ); 
like image 418
Billy Logan Avatar asked Mar 15 '16 16:03

Billy Logan


People also ask

Is promise supported in Internet Explorer?

'Promise' is undefined in Internet Explorer (IE 11)

Are Promises supported in all browsers?

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.

What are correct properties of Promises?

The Promise object supports two properties: state and result. While a Promise object is "pending" (working), the result is undefined. When a Promise object is "fulfilled", the result is a value. When a Promise object is "rejected", the result is an error object.

What is polyfill promise?

Promise Usage. The promise is a constructor which accepts an executor function as a parameter. The executor function has a resolve callback, and a reject callback as its parameter. Once the Promise constructor is called, an async operation is initiated, say, an HTTP API call.


1 Answers

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.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<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> 
like image 153
jfriend00 Avatar answered Oct 13 '22 05:10

jfriend00