I’ve spent days and days on this trying various techniques I have red on here and other forums but just cant get my head a round it.
I’ve tried .map(), I’ve tried global variables, I’ve tried everything I can think of. steep learning curve
I have split one long function into several smaller functions to make the code more readable and just more functional, the below code is called by a main function I’m using for mapping, the purpose of the code below is to go and fetch data from a model (via views.py) and then pass it back to the main function, it will be a data containing names, cities, towns, countries, it worked fine before I split the long function but now wont pass variables.
Where I console.log ‘the objects the towns’ it looks ok in the console but once outside of that fetch Im lost, Ive tried to return the data from within the fetch function mappointobject (which I believe is an array of objects) but it wont, Ive tried to put a ‘await’ on final console.log but nothing, it seems no matter what I’ve tried fails after the closing fetch function brackets }), the main function just says to me ‘undefined’
Below is what I get at the console.log right before the fetch closing brackets
the objects the towns (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
let mappointsobject;
async function radiocontacttownslist() {
fetch(`/conlogger/getradiocontactsdata`, { //this fetch command via views.py gets the data in the radiocontacts list
method: 'POST',
credentials : 'same-origin',
headers: {//'Accept': 'application/json', //Django needs these headers
'X-CSRFToken': getCookie("csrftoken"),
'Content-type': 'application/json' , //Indicates that the request body format is JSON.
'X-Requested-With': 'XMLHttpRequest'
},
})
.then(response => response.json())
//get the promise and when data comes back, take the response and convert and return as JSON
.then(result => {
console.log(result);
mappointsobject = JSON.parse(result) //convert from JSON to javascript object - also see next line
console.log('the objects the towns',mappointsobject) // this is all the objects and all the data from the radio contacts table
}) //end of fetch brackets
console.log('townlisttestoutsideoffetch',mappointsobject)
return mappointsobject;
}
I’ve tried global variables, I’ve tried .map() (totally lost with this but gave it a crack), I’ve tried passing strings and numbers back and they passed back to the main function fine, It doesn’t like the array or there is a timing conflict. I have also tried using ‘await’ at various points in the main function and this function but cant seem to rationalize it.
Looking for guidance, I’m still learning and have a lot to learn, thankyou