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

懵懂的女人 提交于 2019-12-25 08:15:27

问题


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?


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/38747176/how-can-i-add-a-callback-to-a-function-with-multiple-async-calls-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!