getJSONP function to a Promise

getJSONP function to a Promise

本文关键字:Promise to function getJSONP      更新时间:2023-09-26

我有一个从原型函数内部调用的getJSONP函数。我正在传递一个JSON对象到该函数和改变它里面的值,我希望能够使用更新的对象后,它准备好了,但我似乎不能返回对象,只有从回调调用不同的函数,并在那里使用它。

我想我理解承诺的概念,但我怎么能把我的函数变成一个承诺,并在它准备好时使用它?

这是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。

如何使用承诺填充,他们声称它是轻量级的,支持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
    });
});