Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda