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

204
Vistas
How to wait for multiple fetch to complete, aggregate the result and post it to another URL

I am trying to fetch data from multiple URLs, for example consider a.com, b.com, c.com etc. Consider there are ~500 such URLs. Some of these are up and some can be down which is not known at runtime. I need to aggregate the output received from all active URLs and post them to another URL. I am new to js and could not complete the aggregation with the below code. Please let me know what changes are needed here.

<script>
let resultVal="";
async function apiRequest(url) {
    return new Promise(function (resolve, reject) {

        fetch(url)
      .then(function(response) {
        if (!response.ok) {
          throw new Error("HTTP error, status = " + response.status);
        }
        let myRet=response.text();
       // resultVal=resultVal+"<br\>"+url+" ::: "+myRet;
        return myRet;
      })
      .then(function(text) {
        resultVal=resultVal+"Url: "+url+"Inner content::: "+text+"<br>";
      })
      .catch(function(error) {
      console.log("Error"+error); 
      })
});

}

async function getData() {
let urlList = ["http://www.a.com", "http://www.b.com", "http://www.c.com"];

Promise.all(urlList.map(u=>apiRequest(u)))
.then(function(res){
    console.log('Promise.all', res);
})
.catch(function(err){
   console.error('err', err);
});
}

async function callFetch() {
const res= await getData();
}

callFetch();
fetch('http://www/xyz.com', {method: 'post', body: 'Response: '+resultVal});

</script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The issues in your code are as follows

apiRequest: returns a new Promise that is never resolved

getData: doesn't wait for Promise.all to resolve

callFetch: is asynchronous, but when called is not waited for

other issues:

getData is async - but you never await
apiRequest is async - but you never await
resultVal could be "built" in any order, depending on the order in which the fetches receive a response.

Fixed code

async function apiRequest(url) {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error("HTTP error, status = " + response.status);
    }
    let text = await response.text();
    return "Url: " + url + "Inner content::: " + text + "<br>";
}

function getData() {
    let urlList = ["http://www.a.com", "http://www.b.com", "http://www.c.com"];

    return Promise.all(urlList.map(u => apiRequest(u)));
}

async function callFetch() {
    let res = await getData();
    return res.join('');
}

callFetch()
.then(resultVal => {
    fetch('http://www/xyz.com', {
        method: 'post',
        body: 'Response: ' + resultVal
    });
})
.catch(err => console.log('err', err));

In a browser where top-level await is allowed, the lines after the callFetch function can also be written

try {
    const resultVal = await callFetch();
    await fetch('http://www/xyz.com', {
        method: 'post',
        body: 'Response: ' + resultVal
    });
} catch(err) {
    console.log('err', err);
}

But I'd hold off using this for now, or do it like this if the code happens to be inside an async function

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