简体   繁体   English

如何在JavaScript中通过多个异步调用向函数添加回调?

[英]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? JavaScript中是否有一种方法可以考虑上述getJSON类的异步调用?

Use Deferred : [ https://api.jquery.com/jquery.deferred/][1] 使用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. 如果您要问的是我的想法,则需要函数中实现callback

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并将您的ajax函数放在需要的地方调用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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