0
function jsoncall(){
    $.getJSON("http://localhost:3000/data", function (data) {...});
    $.getJSON("http://localhost:3000/data", function (data) {...});
}

jsoncall.callback(function(){
    //do stuff
});

Something like the pseudocode above. Is there a method in JavaScript that considers async calls like the getJSON above?

Joel De La Cruz
  • 647
  • 1
  • 6
  • 20
  • Isn't the `function (data) {...}` the callback? :) – Shilly Aug 03 '16 at 15:00
  • 1
    Functionally, `jsoncall` is just like `$.getJSON` - you could simply do `jsoncall = $.getJSON` since they are functionally equal. If you need to **wait** until it's done, then I would recommend looking into `$.Deferred` or ES6 Promises. – chazsolo Aug 03 '16 at 15:08
  • 1
    `function jsoncall(){ return $.getJSON(...) }` and then `jsoncall().then(callback)` But the deferred-implementation of jQuery is imo. something between not good and awful, depending on the version you're using. I'd reccomend you taking a look at "real" promises. – Thomas Aug 03 '16 at 15:25

3 Answers3

1

Use Deferred : [https://api.jquery.com/jquery.deferred/][1]

function jsoncall(){
     var $def = $.Deferred();
    $.getJSON("http://localhost:3000/data", function (data) {

      $def.resolve(data);

    });

    return $def;
}
jsoncall.done(function(data){
    //do stuff
});
Joel De La Cruz
  • 647
  • 1
  • 6
  • 20
Tuhin
  • 3,335
  • 2
  • 16
  • 27
0

If you're asking what I think you are, then you need to implement the callback in the function.

function jsonCall(callback) {
    $.getJSON('http://localhost:3000/data', function(data) {
        ....
        callback(data);
    });
}

jsonCall(function(data) {
    ...
});
m_callens
  • 6,100
  • 8
  • 32
  • 54
  • Wasn't looking for a callback for the getJSON but rather the entire function as a whole because it would have multiple getJSONs, sorry. – Joel De La Cruz Aug 03 '16 at 15:52
0

Async Call Explained(here)

Make a utils.js and put your ajax function there call it where ever required.

//utils.js    
function doAjax(callbackFunc, method, url) {
      var xmlHttpReq = new XMLHttpRequest();
      xmlHttpReq.open(method, url);
      xmlHttpReq.onreadystatechange = function() {

          if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
            callbackFunc(xmlHttpReq.responseText,buttonArrayInit);
          }


      }
      xmlHttpReq.send(null);

    }



    function loadMyJson(categoryValue){
      if(categoryValue==="veg")
      doAjax(print,"GET","http://localhost:3004/vegetables");
      else if(categoryValue==="fruits")
      doAjax(print,"GET","http://localhost:3004/fruits");
      else 
      console.log("Data not found");
    }
Aniket Jha
  • 1,751
  • 11
  • 13