简体   繁体   中英

How can I add a callback to a function with multiple async calls in JavaScript?

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM