问题
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