最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting AsyncAwait function to normal ES5 targetting IE 11 - Stack Overflow

programmeradmin1浏览0评论

So, I´ll be needing your help/assistance with these tasks.

I created a search function using Arrows. After testing, I noticed it's not working in IE 11 alone. it works on other browsers though. I later realized that arrow functions won´t work on IE 11. All efforts to make it work have proved abortive.

Please, find below the arrow function and the JS function which I created from the arrow function and its corresponding JS

Arrow function

<script>
    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async searchText => {
        var res = await fetch('../data/info.json');
        var states = await res.json();

        let matches = states.filter(state => {
            var regex = new RegExp(`^${searchText}`,'gi');
            return state.name.match(regex);
        });

        if(searchText.length === 0){
            matches = [];
            matchList.innerHTML = '';
        }
        outputHtml(matches);
    };

    var outputHtml = matches => {
       if(matches.length > 0){
            var html = matches.map(match =>
                `<div class="card result-list de en">
                   <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
               </div>
`).join('');

                matchList.innerHTML = html;
            }
        };
        search.addEventListener('input', () => searchStates(search.value));
        search2.addEventListener('input', () => searchStates(search2.value));
    </script>

Normal JS function (That I created from the arrow function)

<script>

    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async function searchStates (searchText) {
        var res = await fetch('../data/info.json');
        var states = await res.json();
        var matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), "gi");
            return state.name.match(regex);
        });

        if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
        };

        outputHtml(matches);
    };

    var outputHtml = function (matches) {
        if (matches.length > 0) {
            var html = matches.map(function (match) {
                return "<div class=\"card result-list de en\">\n\t\t<h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n\t</div>\n\t");
            }).join('');
            matchList.innerHTML = html;
        }
    };

    search.addEventListener('input', function () {
        return searchStates(search.value);
    });
    search2.addEventListener('input', function () {
        return searchStates(search2.value);
    });

</script>

JSON File

[
    {
        "name":"Running ",
        "url": "url": ""
    },
    {
        "name":"Javascript",
        "url": "url": ""
    },
    {
        "name":"On old browser",
        "url": "url": ""
    },
    {
        "name":"without arrow",
        "url": "url": ""
    },
    {
        "name":"functions and works well",
        "url": ""
    },
    {
        "name":"Please, help me",
        "url": "url": ""
    },
    {
        "name":"I gladyl appreciate your response",
        "url": "url": ""
    },
]

I have change the arrow function and I notice the Await/Async is not supported by IE 11. Is there anyone out there who can make this code work on IE.11 All assistance and help will be clearly appreciated

Thanks

EDIT

I have been able to use the Babel transpiler: /

This is my HTML

              <div class="search">
              <input type="text" class="searchTerm de" id="searchTerm_de" placeholder="Was suchst du ?" onfocus="this.placeholder=''" onblur="this.placeholder='Was suchst du ?'">
              <input type="text" class="searchTerm en" id="searchTerm_en" placeholder="What are you looking for ?" onfocus="this.placeholder=''" onblur="this.placeholder='What are you looking for ?'">
          </div>
              <ul class="list-group-search" id="result"></ul>
              <br/>
          </div> ```

**and this is the transpiled/piled ES5 for IE 11**


     <script>

            function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error);
          return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

      function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args
      ); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

      var search = document.getElementById('searchTerm_de');
      var search2 = document.getElementById('searchTerm_en');
      var matchList = document.getElementById('result');

      var searchStates =  function () {
              var _ref = _asyncToGenerator(function* (searchText) {
                  var res = yield fetch('./data/info.json');
                  var states = yield res.json();
                  let matches = states.filter(function(state) {
                      var regex = new RegExp(`^${searchText}`, 'gi');
                      return state.name.match(regex);
                  });

                  if (searchText.length === 0) {
                      matches = [];
                      matchList.innerHTML = '';
                  }

                  outputHtml(matches);
              });

              return function searchStates(_x) {
                  return _ref.apply(this, arguments);
              };
          }();

      var outputHtml =function(matches) {
          if (matches.length > 0) {
              var html = matches.map(match => `<div class="card result-list de en">
              <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
      </div>
      `).join('');
              matchList.innerHTML = html;
          }
      };

      search.addEventListener('input', () => searchStates(search.value));
      search2.addEventListener('input', () => searchStates(search2.value));

      </script>

While the JSON file still remains the same.

It's still working on all browsers except IE 11.

Its gettings tiring but I'm not determined to give up

Anyone else knows what could be done at this point to make the code run on IE 11

Thanks

So, I´ll be needing your help/assistance with these tasks.

I created a search function using Arrows. After testing, I noticed it's not working in IE 11 alone. it works on other browsers though. I later realized that arrow functions won´t work on IE 11. All efforts to make it work have proved abortive.

Please, find below the arrow function and the JS function which I created from the arrow function and its corresponding JS

Arrow function

<script>
    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async searchText => {
        var res = await fetch('../data/info.json');
        var states = await res.json();

        let matches = states.filter(state => {
            var regex = new RegExp(`^${searchText}`,'gi');
            return state.name.match(regex);
        });

        if(searchText.length === 0){
            matches = [];
            matchList.innerHTML = '';
        }
        outputHtml(matches);
    };

    var outputHtml = matches => {
       if(matches.length > 0){
            var html = matches.map(match =>
                `<div class="card result-list de en">
                   <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
               </div>
`).join('');

                matchList.innerHTML = html;
            }
        };
        search.addEventListener('input', () => searchStates(search.value));
        search2.addEventListener('input', () => searchStates(search2.value));
    </script>

Normal JS function (That I created from the arrow function)

<script>

    var search = document.getElementById('searchTerm_de');
    var search2 = document.getElementById('searchTerm_en');
    var matchList = document.getElementById('result');

    var searchStates = async function searchStates (searchText) {
        var res = await fetch('../data/info.json');
        var states = await res.json();
        var matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), "gi");
            return state.name.match(regex);
        });

        if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
        };

        outputHtml(matches);
    };

    var outputHtml = function (matches) {
        if (matches.length > 0) {
            var html = matches.map(function (match) {
                return "<div class=\"card result-list de en\">\n\t\t<h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n\t</div>\n\t");
            }).join('');
            matchList.innerHTML = html;
        }
    };

    search.addEventListener('input', function () {
        return searchStates(search.value);
    });
    search2.addEventListener('input', function () {
        return searchStates(search2.value);
    });

</script>

JSON File

[
    {
        "name":"Running ",
        "url": "url": "http://google."
    },
    {
        "name":"Javascript",
        "url": "url": "http://google."
    },
    {
        "name":"On old browser",
        "url": "url": "http://google."
    },
    {
        "name":"without arrow",
        "url": "url": "http://google."
    },
    {
        "name":"functions and works well",
        "url": "http://google."
    },
    {
        "name":"Please, help me",
        "url": "url": "http://google."
    },
    {
        "name":"I gladyl appreciate your response",
        "url": "url": "http://google."
    },
]

I have change the arrow function and I notice the Await/Async is not supported by IE 11. Is there anyone out there who can make this code work on IE.11 All assistance and help will be clearly appreciated

Thanks

EDIT

I have been able to use the Babel transpiler: https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator/

This is my HTML

              <div class="search">
              <input type="text" class="searchTerm de" id="searchTerm_de" placeholder="Was suchst du ?" onfocus="this.placeholder=''" onblur="this.placeholder='Was suchst du ?'">
              <input type="text" class="searchTerm en" id="searchTerm_en" placeholder="What are you looking for ?" onfocus="this.placeholder=''" onblur="this.placeholder='What are you looking for ?'">
          </div>
              <ul class="list-group-search" id="result"></ul>
              <br/>
          </div> ```

**and this is the transpiled/piled ES5 for IE 11**


     <script>

            function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error);
          return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

      function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args
      ); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

      var search = document.getElementById('searchTerm_de');
      var search2 = document.getElementById('searchTerm_en');
      var matchList = document.getElementById('result');

      var searchStates =  function () {
              var _ref = _asyncToGenerator(function* (searchText) {
                  var res = yield fetch('./data/info.json');
                  var states = yield res.json();
                  let matches = states.filter(function(state) {
                      var regex = new RegExp(`^${searchText}`, 'gi');
                      return state.name.match(regex);
                  });

                  if (searchText.length === 0) {
                      matches = [];
                      matchList.innerHTML = '';
                  }

                  outputHtml(matches);
              });

              return function searchStates(_x) {
                  return _ref.apply(this, arguments);
              };
          }();

      var outputHtml =function(matches) {
          if (matches.length > 0) {
              var html = matches.map(match => `<div class="card result-list de en">
              <h6><span class="my-result"><a href="${match.url}" target="_blank">${match.name}</a> </h6></span>
      </div>
      `).join('');
              matchList.innerHTML = html;
          }
      };

      search.addEventListener('input', () => searchStates(search.value));
      search2.addEventListener('input', () => searchStates(search2.value));

      </script>

While the JSON file still remains the same.

It's still working on all browsers except IE 11.

Its gettings tiring but I'm not determined to give up

Anyone else knows what could be done at this point to make the code run on IE 11

Thanks
Share Improve this question edited Nov 25, 2019 at 14:41 Olasunkanmi asked Nov 19, 2019 at 12:19 OlasunkanmiOlasunkanmi 99215 silver badges23 bronze badges 10
  • 1 await, async, template literals and arrow functions are not supported in ES5. Arrow functions are very similar to function(){}. Template literals can be replaced by something like: "..." + variable1 + "..." + variable2. async and await need to be replaced with Promises (or polyfill) – nick zoum Commented Nov 19, 2019 at 12:30
  • you need babel – Vishnu Bhadoriya Commented Nov 19, 2019 at 12:31
  • @VishnuBhadoriya I used babel as well, and still the error persists. Can you help me look into this code please ? Thanks – Olasunkanmi Commented Nov 19, 2019 at 12:56
  • 1 @nickzoum Thanks for the quick response. So, what would you advice that I change in the code Thanks – Olasunkanmi Commented Nov 19, 2019 at 12:58
  • @AdenijiOlasunkanmi if your error is related to async,awit in babel then refer this link – Vishnu Bhadoriya Commented Nov 19, 2019 at 13:13
 |  Show 5 more ments

4 Answers 4

Reset to default 3 +25

Check this link

I used babel repl to generate IE patible code. You should follow the instructions @David Barshav mentioned but you need to configure your babel correctly to work with IE 11. Also you should check preset-env for babel.

Edit : Well the code transpiled below is just a workable version of javascript. But the missing part is fetch is not supported by IE 11. You have to use a polyfill for that or use XHR request or use a library that simplifies making XHR requests (like jquery).

Github Fetch poyfill. BluebirdPromise polyfill.

The generated code :

var search = document.getElementById('searchTerm_de');
var search2 = document.getElementById('searchTerm_en');
var matchList = document.getElementById('result');

var searchStates = function searchStates(searchText) {
  var res, states, matches;
  return regeneratorRuntime.async(function searchStates$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return regeneratorRuntime.awrap(fetch('../data/info.json'));

        case 2:
          res = _context.sent;
          _context.next = 5;
          return regeneratorRuntime.awrap(res.json());

        case 5:
          states = _context.sent;
          matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), "gi");
            return state.name.match(regex);
          });

          if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
          }

          ;
          outputHtml(matches);

        case 10:
        case "end":
          return _context.stop();
      }
    }
  });
};

var outputHtml = function outputHtml(matches) {
  if (matches.length > 0) {
    var html = matches.map(function (match) {
      return "<div class=\"card result-list de en\">\n\t\t<h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n\t</div>\n\t");
    }).join('');
    matchList.innerHTML = html;
  }
};

search.addEventListener('input', function () {
  return searchStates(search.value);
});
search2.addEventListener('input', function () {
  return searchStates(search2.value);
});

To enable support for async in IE 11 you need to make sure you are including the Regenerator Runtime in your page. This can either be loaded directly, or included via babel-transform-runtime.

the easiest way is to use bable and specify to use a presets for IE11

.bablerc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "ie >= 11"]
      },
        "useBuiltIns": true
    }],

  ]
}

and use CLI with flag --presets babel-preset-es2015-ie

Using bable online tester

Bable Tester

I just converted to old version using babel preset,run-time and re-generator and It'll work in IE.

var search = document.getElementById('searchTerm_de');
var search2 = document.getElementById('searchTerm_en');
var matchList = document.getElementById('result');

var searchStates = function searchStates(searchText) {
  var res, states, matches;
  return _regenerator.default.async(function searchStates$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return _regenerator.default.awrap(fetch('../data/info.json'));

        case 2:
          res = _context2.sent;
          _context2.next = 5;
          return _regenerator.default.awrap(res.json());

        case 5:
          states = _context2.sent;
          matches = states.filter(function (state) {
            var regex = new RegExp("^".concat(searchText), 'gi');
            return state.name.match(regex);
          });

          if (searchText.length === 0) {
            matches = [];
            matchList.innerHTML = '';
          }

          outputHtml(matches);

        case 9:
        case "end":
          return _context2.stop();
      }
    }
  });
};

var outputHtml = function outputHtml(matches) {
  if (matches.length > 0) {
    var html = matches.map(function (match) {
      return "<div class=\"card result-list de en\">\n               <h6><span class=\"my-result\"><a href=\"".concat(match.url, "\" target=\"_blank\">").concat(match.name, "</a> </h6></span>\n           </div>\n");
    }).join('');
    matchList.innerHTML = html;
  }
};

search.addEventListener('input', function () {
  return searchStates(search.value);
});
search2.addEventListener('input', function () {
  return searchStates(search2.value);
});

I'm using presets for this code to transform from asyn to IE! If it's not working, let us know, so we can assist you better!

Happy codin'!

发布评论

评论列表(0)

  1. 暂无评论