I searched for a long time and although there are many questions with similar keywords, none of them share the same intricacies, so let me explain my problem:
I have a function (getProjectData), that has to be called (it is a system wide thing) to get all data from a particular admin section of a cms. My problem comes from a conditional check, where if A one object is blank, where if B, it needs to contain the result of more than 1 ajax calls. The whole data object gets retuned in this function. Code so far:
function getProjectData() {
var code = "some id";
var frozen = true;
var obj = {
code: code,
frozen: true,
localData: "",
};
// here is the point where the object gets returned with a black localData
// or splits to get a few ajax calls
if ( !obj.frozen ) return obj;
else {
getLocalData ( code ).then( function ( data ) {
// ideally, here i would make the parent return obj, but this time with added localData data
obj.localData = data;
parent.return obj;
} );
}
}
function getLocalData ( code ) {
var promise = new Promise ( function ( resolve, reject ) {
var apiReq = "apiUrl";
var chartsReq = "anotherApiUrl";
var res;
$.when(
// api response
$.ajax({
url: apiReq + code,
type: "get",
success: function ( data ) {
return data;
},
error: function ( error ) {
return error;
}
}),
// another ajax call..
$.ajax({ ... }),
// another ajax call..
$.ajax({ ... })
).then(
function ( a, b, c ) {
data = {
response: a
...... for b and c
};
resolve ( data );
},
function ( error ) {
reject ( error );
}
);
} );
return promise.then(
function (data) {
return data;
},
function ( error ) {
console.log ( error );
}
);
}
My problem is that since (and i tried with other ways as well..) all the returns are in a function within other functions, there is no way to return the Obj object after the localData has been added.
I might have over-engineered it but i tried many different ways and since the getProjectData is called by a save button and values need to be returned rather than say, appended to the DOM, i am not sure what to do!
I know that in asynchronous requests, the function has to return before the result is available, where we would usually use callbacks, but a callback will not be able to return something. I could use synchronous requests but i know they are going to be deprecated..
Any ideas?