I have a similar question to Elegant solution to conditional AJAX call, where a parameter is loaded via an API call and cached before subsequent AJAX calls, with the additional requirement that this is run in parallel to another AJAX call.
Some pseudocode for this would be:
var myParameter;
function myUpdate() {
$.when(
// always make one AJAX call
$.ajax(params1),
(async () => {
// retrieve the parameter if not already loaded
if (myParameter == null) {
let response = await fetch(someParams);
myParameter = doStuff(response); // some irrelevant magic here
}
// if the myParameter is 0, do nothing (return a fulfilled promise)
// otherwise make an AJAX call with params2 + myParameter
return myParameter == 0 ? $.when() : $.ajax(Object.assign(params2, {data: { value: myParameter }}));
})()
).then(handleData); // finally do some stuff with the responses in the handleData() function
}
The above doesn’t seem to work as $.when()
does weird things with different types of promises, which has resulted in this abomination:
var myParameter;
function myUpdate() {
$.when(
$.Deferred((dfrd) => {
$.ajax(params1).then((response) => {dfrd.resolve(response)});
}).promise(),
$.Deferred((dfrd) => {
if (myParameter == null) {
fetch(someParams).then((response) => {
myParameter = doStuff(response);
if(myParameter != 0) {
$.ajax(Object.assign(params2, {data: { value = myParameter }})).then((response) => {dfrd.resolve(response)});
} else {
dfrd.resolve();
}
});
} else {
if(myParameter != 0) {
$.ajax(Object.assign(params2, {data: { value = myParameter }})).then((response) => {dfrd.resolve(response)});
} else {
dfrd.resolve();
}
}
}).promise()
).then(handleData);
}
While it works, and I could tidy it up a bit using this answer to remove the redundancy, I’m not sure it’s the right way to do this.
Daniel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.