Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
.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"); //
        })
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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"); //
        });
about 4 years ago · Juan Pablo Isaza Denunciar

0

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!"); //
    });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda