Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Cómo esperar a que se complete la búsqueda múltiple, agregar el resultado y publicarlo en otra URL

Estoy tratando de obtener datos de varias URL, por ejemplo, considere a.com, b.com, c.com, etc. Considere que hay ~ 500 URL de este tipo. Algunos de estos están activos y otros pueden estar inactivos, lo que no se conoce en tiempo de ejecución. Necesito agregar la salida recibida de todas las URL activas y publicarlas en otra URL. Soy nuevo en js y no pude completar la agregación con el siguiente código. Por favor, hágame saber qué cambios son necesarios aquí.

 <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 answers
Answer question

0

Los problemas en su código son los siguientes

apiRequest : devuelve una new Promise que nunca se resuelve

getData : no espera a que Promise.all se resuelva

callFetch : es asincrónico, pero cuando se llama no se espera

otros asuntos:

getData es async , pero nunca await
apiRequest es async , pero nunca await
resultVal podría "construirse" en cualquier orden, según el orden en que las búsquedas reciban una respuesta.

Código fijo

 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));

En un navegador donde se permite la await de nivel superior, las líneas después de la función callFetch también se pueden escribir

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

Pero dejaría de usar esto por ahora, o lo haría así si el código está dentro de una función async

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!