There is a mistake in the following code but I can't figure it out. I believed that when I do Promise.all(...).then, all promises should be finished at that point, but it does not look like it. . The code just grabs a few jsons from an api, then adds a few html elements to the DOM. But, somehow those new elements dont register in the .then part of the Promise.all.
let urls = [];
urls.push(someurl);
urls.push(someurl2);
Promise.all(urls.map(url => {
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
... // do something with the current json and add some <option> elements to the DOM
let options = document.querySelectorAll('option');
console.log(options); //is filled with the correct options!
})
})).then(data => {
let options = document.querySelectorAll('option');
console.log(options); // IS EMPTY!!! I expected to see the two sets of the <option> elements
});
The resulting HTML looks like it should on the frontend, but the DOM in .then is not in the state I expect it to be. Because of this I am having issues with the materializecss library, since I cannot fill my select dropdown with elements. It's like they have not been created yet at the point where I initialize the select dropdown in .then . Thanks for the help!
I don't know exactly why the Promise.all(...).then executed even without the correct return, but this fixed it.
Without the return
that you were missing, you were passing Promise.all()
an array of undefined
values. Since there were no promises in that array, Promise.all()
had nothing to wait for so it called its .then()
handler immediately. That's why it executed without waiting for completion. You have to pass Promise.all()
an array of promises if you want it to wait.