Skip to content
Advertisement

Asynchronous loading of select list options

I’m retrieving information on Municipality names, ZipCodes, etc. from a public service provider (DAWA) using AJAX. At first I had an issue retriving the data until I made the transfer asyncronous, thus ajaxGetMunicipalitiesFromDAWA is an asyncronous function. I have checked ajaxGetMunicipalitiesFromDAWA and it loads data correctly.

The I try to update my selectlist using the data, but it seems the update occurs before Municipalies is loaded. I have tried to make loadMunicipalities asyncronous as well, but still I end up having an empty option list.

Please help

HTML code:

JavaScript

JavaScript:

JavaScript

Advertisement

Answer

Couple of things, XMLHttpResquest.send does not return a promise. So awaiting send will just await for the an empty microtask to complete and not actually the request. What you’d want to do is just wrap the request in a Promise which will be handled by the async FSM. You also need to actually call loadMunicipalities so that the list is actually populated. Below is a working example.

JavaScript
JavaScript

So this works as is, but since you are using semi modern apis, id recommend that you use fetch as it handles almost all the fixes applied but makes the code much less verbose.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement