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?

3
  • Isn't the function (data) {...} the callback? :) Commented Aug 3, 2016 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. Commented Aug 3, 2016 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. Commented Aug 3, 2016 at 15:25

3 Answers 3

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wasn't looking for a callback for the getJSON, deferred part was what I wanted, setting as answer, thank you.
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) {
    ...
});

1 Comment

Wasn't looking for a callback for the getJSON but rather the entire function as a whole because it would have multiple getJSONs, sorry.
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");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.