I'm quite new with JS, not so much with programming in general (C++, Python...) The goal I have is quite basic but I can't find a simple and elegant solution to my problem. I'd like to have a single html page with a header + a table. This table should display json data I get to from an existing 3p API.
What I need my code to do
- Execute on loading the html page (not using a buton) > I use <script...>
- The code should start by getting the api data (I use Axios)
- Run a formatting function (to change multi-layer json to an array of key: values objects)
- Update the display page (using vue JS)
Where I'm at now Code start on loading > OK Code gets the data using axios > OK (almost) run formating function > NOT OK since this function start before the end of the axios get function is finished
The way i'd like to structure my code : (pseudo code) index.js
const formattedDataArray = [];
const unformattedData;
function getAPIData() {
use axios to get data;
return unformattedData;}
function formatData() {
transform unformatedData;}
function updateHTMLWithData() {
update html using viewJS;}
/*start execution here*/
unformattedData = getAPIData();
formatedData = formatData();
updateHTMLwithData();
The getAPIData function works
The transformData fucntion works
BUT...
because of the time it takes to get the data from the server, the transformData()
function is executed before the end of the getAPIData()
function (I checked with a lot of console.log()
)
Here is my code. Could you please point me in the right direction as if you were talking to a 3year old ? ;) Thanks
let jsonData = [];
const formattedData = [];
async function getAPIData() {
console.log('Start getAPIData');
// fetch data from a url endpoint
const data = await axios.get('https://myurl.domain/api', {
headers: {
crossDomain: true,
'app-id' : 'won't tell',
'app-secret': 'won't tell either'
}
});
console.log(data.data);
console.log('End getAPIData');
return data;
}
function formatData() {
console.log('Sart formatData');
/* do relevant stuff here with jsonData to formattedData*/
console.log('End formatData');
}
/*main executing here*/
console.log('Start Main Code');
jsonData = getAPIData();
console.log('After getAPIDate');
formatData();
console.log(formattedData);
console.log('Fin du script');