After working with the helpful comments below, the solution settled in as follows:
async function grab_sysLvl_phase_program_mission() {
const sysLvl = get("/api/SystemLevelList_url/").catch(err=>showErrorAlert(err));
const phase = get("/api/mmSelectorPhase_url/").catch(err=>showErrorAlert(err));
const program = get("/api/ProgramList_url/").catch(err=>showErrorAlert(err));
const mission = get("/api/MissionList_url/").catch(err=>showErrorAlert(err));
return await Promise.all([sysLvl,phase,program,mission])
}
//passed into .then(), takes the data from promise and formats it into an object
function createDataObject(obj){
let data = {
sysLvlList: obj[0],
phaseList: obj[1],
programList: obj[2],
missionList: obj[3]
}
return data;
}
//stores the promise as constant
const defaultValues = grab_sysLvl_phase_program_mission();
//simple usage, can be called whenever the data is required without pinging the server again
defaultValues.then(obj => {
const testing = createDataObject(obj);
console.log(testing);
console.log(testing.sysLvlList);
});
Thanks again for all the help.
Original Post Below -------------------
I have to make several calls to an API to get default data used throughout the site (the data is independent of each other, no key constraints). I am attempting to create a function that returns an object with all the returned data from the various calls. The API leverages a Django Restframework.
I was looking for data to be in this format:
defaultValues ={
sysLvlList: {},
phaseList: {},
programList:{}
missionList:{}
}
Then be able to access the data through dot notation, defaultValues.sysLvlList etc. What I ended up doing was:
let defaultValues = {};
async function getSystemLevel_phase(){
const sysLvl = get("/api/SystemLevelList_url/").then(r=>defaultValues.sysLvlList = r).catch(err=>showErrorAlert(err));
const phase = get("/api/mmSelectorPhase_url/").then(r=>defaultValues.phaseList = r).catch(err=>showErrorAlert(err));
const program = get("/api/ProgramList_url/").then(r=>defaultValues.programList = r).catch(err=>showErrorAlert(err));
const mission = get("/api/MissionList_url/").then(r=>defaultValues.missionList = r).catch(err=>showErrorAlert(err));
await Promise.all([sysLvl,phase,program,mission]);
}
getSystemLevel_phase();
console.log(defaultValues);
console.log(defaultValues.sysLvlList);
Which logged unidentified when attempting to use dot notation (see image below for reference). When working in the browser console, I would access the data. I believe the promise are fulfilling after the site renders.
Ideally, I would prefer to not have to define the variable outside of the function, but instead set the function to a variable like:
const defaultValue = getSystemLevel_phase()
Any help would be appreciated, thank you