-1
I’m having difficulty a few days, I’m beginner and even reading the documentation sometimes apply is not as simple as it seems, I understand that I lack Exp to understand.
my problem: I’m using the google maps Javascript api and an API I made to load the points (markers) on the map. However, sometimes it loads the map and does not load the dots, I can see this because I used the console.log(marcadores.length)
to check and it comes zeroed, then I update the page and everything loads correctly, but can also load empty again.
Could someone please give me a light?
I’d like to call the function initMap()
only after loading the array with the data that came from my DB API, how to proceed?
Below is the code I use to load the data from the api:
var marcadores = [];
function carregaPosicoes(){
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:5000/Truck/Veiculos", true);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const data = JSON.parse(this.response);
data.forEach(veiculo => {
marcadores.push(veiculo);
});
};
};
initMap();
request.send();
};
can move
initMap();
into the Functiononreadystatechange
. Here the concept is when running the linerequest.open
the code flow already goes to the next line which isrequest.onreadystatechange
, but this wait line returns from the API, a Promise as we call it, so since there’s nothing yet, go to the next line which is theinitMap()
and there is still no data, because the call has not yet returned, so you need to move this line inside the Function– Ricardo Pontual
From what I understand, Voce could call the function
init
within theif
, after theforEach
. Tested it that way?– Cmte Cardeal
@Ricardopunctual 4 seconds faster than I XD
– Cmte Cardeal
:D was almost instantaneous @Cmtecardeal, not to miss the joke, I was more like "Punctual" ;)
– Ricardo Pontual
Your question has nothing to do with async/await. It has more to do with the object
XMLHttpRequest
, then I edited the question title.– Cmte Cardeal
@Ricardopunctual hahahahah hahaha. Noting that the question has more to do with
XMLHttpRequest
than async/await– Cmte Cardeal
@Cmtecardeal, thanks for the editing, is that when I searched on "expect to load object and perform function" always fall into async/await. I will test the suggestions here and go back to comment on what worked. thank you all so far.
– GFS
I added a responsta to demonstrate what @Piovezan replied
– Ricardo Pontual