javascript - Promise 的 getJSONP 函数

标签 javascript promise jqlite

我有一个从原型(prototype)函数内部调用的 getJSONP 函数。我将一个 JSON 对象传递给该函数并更改其中的值,我希望能够在准备好后使用更新的对象,但我似乎无法返回该对象,只能从回调中调用不同的函数并使用它那里。

我认为我理解 promise 的概念,但是我如何将我的函数更改为 promise 并在准备好时使用它?

这是 getJSONP 函数:

function getJSONP(url, success) {
  var ud = '_' + +new Date,
    script = document.createElement('script'),
    head = document.getElementsByTagName('head')[0] || document.documentElement;

  window[ud] = function(data) {
    head.removeChild(script);
    success && success(data);
  };

  url += '?callback=' + ud;
  script.src = url;
  head.appendChild(script);
};

这就是我使用它的方式:

MyClass.prototype.mySpecialFunction = function(myObject) {
    getJSONP(myURL,function(data) {
      //doing alot of stuff
      ...
      //myObject.myArr = code the pushes a lot of stuff into an array
      workWithTheNewArray(myObject) // where i work with the full array
    });
});

请考虑到我没有使用 jQuery(因为性能和大小),但我正在使用 jqlite .

最佳答案

使用 pormise polyfill 怎么样? ,他们声称它是轻量级的并且支持 IE,那么你可以尝试下面的代码:

function getJSONP(url, success) {
  return new Promise(function(resolve, reject){
    var ud = '_' + +new Date,
    script = document.createElement('script'),
    head = document.getElementsByTagName('head')[0] || document.documentElement;

    window[ud] = function(data) {
      head.removeChild(script);
      resolve(data);
    };

    url += '?callback=' + ud;
    script.src = url;
    head.appendChild(script);
  });
};

MyClass.prototype.mySpecialFunction = function(myObject) {
    return getJSONP(myURL).then(function(data) {
      //doing alot of stuff
      ...
      //myObject.myArr = code the pushes a lot of stuff into an array
      workWithTheNewArray(myObject) // where i work with the full array
    });
});

关于javascript - Promise 的 getJSONP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31672683/

相关文章:

javascript - 如何正确输入这个 `makeCancellable`函数并使Flowtype停止提示?

angularjs - 在 Mocha 测试套件中触发 AngularJS 指令上的点击事件

javascript - 使用 JQuery html() 添加链接在 IE6 上不可点击

javascript - WinRT Metro 风格的 HTML5/JavaScript 应用程序是如何打包和保护的

javascript - 对 promise 感到困惑

javascript - 在 Controller 中使用工厂返回未定义

javascript - 通过 ng-class 添加类时,angular.element 不起作用

javascript - AngularJS - 获取元素属性值

JavaScript 数据库

javascript - 从 AngularJS 中的模板获取编译后的 html