问题
I want to use JavaScript asynchronous, as it was intended. I want to assign the recieved data/objects to as many variables as I'll need (DataModel01, DataModel02, DataModel03 and so on). The idea is that my need for API data change all the time, and I want to only have to define once where to get the data (API endpoint), and in what local variable/object to store it.
The way I'm doing it, it returns the object with recieved data from the fetchDataJSON() function. However, how do I make the return wait for the Ajax to finish? I've tried several things, including timers and callbacks, and nothing works at all.
I saw the other questions regarding ajax and async, and generally it was suggested to use callbacks. So I believe I might be offtrack, but I need a hand to figure out a way to deal with this gracefully. Do I really need to mess with timers and ugly solutions like that?
function fetchDataJSON(endpointUrl) {
var returnObj = [];
// Ajax call
$.ajax({
type: "GET",
url: endpointUrl,
dataType: 'json',
async: true,
success: updateData,
error: handleError
});
function updateData(data) {
returnObj = data;
}
function handleError(XHR, message, error) {
console.log("Failed XHR");
}
return returnObj; // Return JSON object
}
var DataModel01 = fetchDataJSON( "http://mydata.com/endpoint/sweetjson" );
var DataModel02 = fetchDataJSON( "http://mydata.com/endpoint/somethingelse" );
EDIT: I found a working solution now, yihar. I've marked the answer by Karman as accepted, as it was the one closest to the solution. My final solution, which was also inspired by a coworker, is as follows:
var DataModel01 = [];
var DataModel02 = [];
function fetchDataJSON(endpointUrl, callbackWhenDone) {
// Ajax call
$.ajax({
type: "GET",
url: endpointUrl,
dataType: 'json',
async: true,
success: updateData,
error: handleError
});
function updateData(data) {
callbackWhenDone(data);
}
function handleError(XHR, message, error) {
console.log("Failed XHR");
}
}
fetchDataJSON(
"http://mydata.com/endpoint/sweetjson",
function(newData) { DataModel01 = newData; }
);
fetchDataJSON(
"http://mydata.com/endpoint/somethingelse",
function(newData) { DataModel02 = newData; }
);
回答1:
function fetchDataJSON(endpointUrl, callback) {
function updateData(data) {
returnObj = data;
callback(returnObj)
}
fetchDataJSON( "http://mydata.com/endpoint/sweetjson", getJson );
enter code here
function getJson(returnObj)
{
//do work with returnObj
}
回答2:
declare var DataModel1 in first line of the code.
in success method (updateData) assign the data to DataModel1 directly. in success method itself you can differentiate with url for datamodel2
来源:https://stackoverflow.com/questions/40403461/wait-for-ajax-call-in-function-to-end-then-return-object-to-an-outside-variable