将具有ES6承诺的函数转换为没有ES6承诺的函数

时间:2019-01-28 17:54:24

标签: javascript es6-promise

我有使用ES6 promise的代码,并且我想将其转换为没有Promise的代码。 代码很长,但是promise只在这一部分中使用:

function(e, t, r) {
        "use strict";
        e.exports = function(e) {
            var t = new XMLHttpRequest;
            return new Promise(function(r, n) {
                t.onreadystatechange = function() {
                    if (4 == this.readyState)
                        if (200 == this.status) {
                            var e = JSON.parse(this.response);
                            r(e)
                        } else {
                            var t = JSON.parse(this.response);
                            n(t)
                        }
                }, t.onerror = function(e) {
                    n(new Error(this.statusText))
                }, t.open("GET", e, !0), t.send(null)
            })
        }
    }, function(e, t, r) {
        "use strict";

        function n(e, t) {
            o.options.key = e;
            for (var r in t) o.options[r] = t[r]
        }
        var o = r(3),
            u = r(4);
        e.exports = function(e, t, r, i) {
            if (!t && "function" == typeof i) return i(new Error("API Key is required"));
            if (!t) throw new Error("API Key is required");
            n(t, r);
            var s = u.stringify(o.options);
            if ("function" != typeof i) return e(o.URL + s);
            e(o.URL + s).then(function(e) {
                return i(null, e)
            }).catch(function(e) {
                return i(e)
            })
        }
    } 

1 个答案:

答案 0 :(得分:1)

我已将其转换为基于回调的。回调格式如下:

callback(err, data)如果err不为null,则发生错误,否则err参数为null,而data参数为该值。

function(e, t, r) {
  "use strict";
  e.exports = function(e, callback) {
      var t = new XMLHttpRequest;
      t.onreadystatechange = function() {
          if (4 == this.readyState)
              if (200 == this.status) {
                  var e = JSON.parse(this.response);
                  callback(e);
              } else {
                  var t = JSON.parse(this.response);
                  callback(null, t)
              }
      }, t.onerror = function(e) {
          callback(new Error(this.statusText))
      }, t.open("GET", e, !0), t.send(null)
  }
}, function(e, t, r) {
  "use strict";

  function n(e, t) {
      o.options.key = e;
      for (var r in t) o.options[r] = t[r]
  }
  var o = r(3),
      u = r(4);
  e.exports = function(e, t, r, i) {
      if (!t && "function" == typeof i) return i(new Error("API Key is required"));
      if (!t) throw new Error("API Key is required");
      n(t, r);
      var s = u.stringify(o.options);
      if ("function" != typeof i) return e(o.URL + s);
      e(o.URL + s).then(function(e) {
          return i(null, e)
      }).catch(function(e) {
          return i(e)
      })
  }
} 

或者您可以使用Promise pollyfill:

https://github.com/stefanpenner/es6-promise

https://www.npmjs.com/package/promise-polyfill