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

210
Views
¿Cómo usar "async" o "await" dentro del bucle for en mi código?

Estoy tratando de desarrollar una herramienta para desechar y publicar datos desde / hacia sitios web usando "titiritero", escribí dos módulos, uno para leer las URL del archivo JSON y tiene el bucle for que incluye la función del otro módulo que visita el sitio web y desechar los datos.

Cuando construí las funciones y ejecuté el código, por primera vez mi PC se bloqueó y no pude identificar el problema, hasta que encontré una publicación que explicaba sobre "async" y "await" en NodeJS, traté de entender cómo aplicarlo a mi código, pero no pude.

Así que estoy tratando exactamente de pasar por el bucle para visitar el sitio web, luego desecho los datos, después de terminar desde el primer elemento, debería ir al siguiente elemento del bucle en lugar de ejecutar todos los elementos a la vez, lo que hace que la PC colgar.

getUrlsAndVisitWebsite.js

 const puppeteer = require('puppeteer') const fs = require('fs'); var visitWebsite= require('/home/projtect1/visitWebsite.js'); async function getUrlsAndVisitWebsite(){ fs.readFile("/home/project1/urls.json", "utf8", (err, jsonString) => { if (err) { console.log("File read failed:", err); return; } var jsonOBj= JSON.parse(jsonString); for (let i = 0; i < 2; i++) { var postPath = JSON.parse(jsonOBj[i]).url; // here I'm using puppeteer to visit websites and scrab data visitWebsite(postPath) } }); } getUrlsAndVisitWebsite()

visitWebsite.js

 const puppeteer = require('puppeteer') var fs = require('fs'); async function visitWebsite(postPath){ const browser = await puppeteer.launch({ headless: false, waitUntil: 'networkidle2' }) const page = await browser.newPage() await page.setViewport({ width: 0, height: 0}); //Loading Cookie from file const cookiesString = await fs.readFileSync('./cookies.json'); const Writecookies = JSON.parse(cookiesString); await page.setCookie(...Writecookies); // GO to the target URL for post console.log(postPath) await page.goto(postPath) //Wait for the selector that list the elements await page.waitForSelector('#gridPostListing'); } module.exports=visitWebsite;
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Su función visitWebsite es asíncrona, debe esperarla en getUrlsAndVisitWebsite. Tal como está ahora, solo devuelve una promesa, por lo tanto, se cuelga.

Simplemente agregue esperar antes de su llamada visitWebsite.

about 4 years ago · Santiago Trujillo 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!