Search code examples
javascriptpromisejqlite

getJSONP function to a Promise


i have a getJSONP function that is being called from inside a prototype function. I am passing a JSON object to that function and changing values inside it, i want to be able to use the updated object after it's ready but i can't seem to return the object, only call a different function from the callback and use it there.

I thnink i understand the concept of promises but how can i change my function into a promise and use it when it is ready?

this is the getJSONP function:

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);
};

And this is how i use it:

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
    });
});

please take into account that i am not using jQuery (because of performance and size), but i am using jqlite.


Solution

  • how about using a pormise polyfill, they claim it is lightweight and supports IE, then you can give the below code a try:

    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
        });
    });