'.then running before data is returned from fetch
I want show_name()
to run and then call another function. I don't understand why show_name().then
fails. I'm probably overlooking something.
async function show_name() {
flights_xml.forEach( (flt, i) => {setTimeout(() => {
if (document.getElementById('show_dx_name').checked) {
let serial_from_xml = flt.children[7].innerHTML;
// async function getDxrName633() {
const serialNumber = { serial_from_xml };
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(serialNumber)
};
fetch('/recall633', options)
.then(response => response.json())
.then(json => {
let parser = new DOMParser();
let a633XML = parser.parseFromString(json, "application/xml");
Formats = a633XML.querySelector('Formats');
a633 = Formats.children[1].innerHTML;
a633b4ParsedToXML = $('<textarea />').html(a633).text();
a633 = parser.parseFromString(a633b4ParsedToXML, "text/xml")
console.log(a633)
console.log("Author: " + a633.children[0].children[4].children[0].children[0].innerHTML)
})
// }
// getDxrName633().then(()=>{
// console.log("This will work but I don't need it to run every time...it's a waste");
// })
} // END IF ..show
}) // END SetTimeout
}) // END foreach
} // END async show_name
show_name().then(() => {
console.log("Why is this running before the fetch .then ?? ...weird"); //
})
Solution 1:[1]
TL;DR; something.forEach()
doesn't wait.
Tried both, but @jamomani 's answer gave errors due to flt being an object. It turns out map doesn't work if it's an obj.
My answer is based on @gabrielrincon 's answer. The promise turned out to be unnecessary and needed to await response.json().
for (const flt of flights_xml) {
console.log(flt) // flt is an object
if (document.getElementById('show_dx_name').checked) {
let serial_from_xml = flt.children[7].innerHTML;
console.log(serial_from_xml)
// async function getDxrName633() {
// let serial_from_xml = 21348
const serialNumber = { serial_from_xml };
console.log(serialNumber)
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(serialNumber)
body: JSON.stringify(serialNumber)
};
let response = await fetch('/recall633', options)
// .then(response => response.json()) <-- this also works
// .then(json => {
let json = await response.json()
// let json = response.json(); <-- Doesn't work; need to await
let parser = new DOMParser();
let a633XML = parser.parseFromString(json, "application/xml");
Formats = a633XML.querySelector('Formats');
a633 = Formats.children[1].innerHTML;
a633b4ParsedToXML = $('<textarea />').html(a633).text(); // converts from encoded to xml tags
a633 = parser.parseFromString(a633b4ParsedToXML, "text/xml")
console.log(a633)
console.log("Author: " + a633.children[0].children[4].children[0].children[0].innerHTML)
} // END IF ..show
} // end for
} // END async show_name
show_name()
.then(() => {
console.log("This is finally waiting for the fetch .then - excellent!"); //
});
Solution 2:[2]
Here is a simplified version which you can apply to you code.
const promArr = flights_xml.map( async (flt, i) => {
const res = await fetch('/recall633', options)
return await res.json()
})
const doneAll = await Promise.all(promArr)
console.log('Fetched all')
doneAll.forEach( fetched => {
// Do your DOM parsing here
}
Solution 3:[3]
Look, I refactor you code...
Basically, I change forEach for a forof... and, I used await... I hope can help you. And I used a Promise response...
async function show_name() {
return new Promise( async (resolve) => {
for (const flt of flights_xml) {
if (document.getElementById('show_dx_name').checked) {
let serial_from_xml = flt.children[7].innerHTML;
// async function getDxrName633() {
const serialNumber = { serial_from_xml };
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(serialNumber)
};
const response = await fetch('/recall633', options);
const json = response.json();
let parser = new DOMParser();
let a633XML = parser.parseFromString(json, "application/xml");
Formats = a633XML.querySelector('Formats');
a633 = Formats.children[1].innerHTML;
a633b4ParsedToXML = $('<textarea />').html(a633).text();
a633 = parser.parseFromString(a633b4ParsedToXML, "text/xml")
console.log(a633)
console.log("Author: " + a633.children[0].children[4].children[0].children[0].innerHTML)
} // END IF ..show
}
resolve('And now?');
});
} // END async show_name
show_name()
.then(() => {
console.log("Why is this running before the fetch .then ?? ...weird"); //
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Adrian |
Solution 2 | |
Solution 3 | gabrielrincon |