1

I have a function that uses a for loop to insert data in database. But db.end() is being called before the loop is finished executing. I've also tried to convert db.query into a promise using the util library, and same thing happens. What do i need to change to ensure that .end() doesn't get called until the for loop is finished?

async function processData(err, data) {
  if (err) {
    throw err;
  }
  let db = mysql.createConnection({ ... });

  let statement = "INSERT INTO Kijiji SET ?";
  db.connect();
  for (let i = 0; i < data.length; i++) {
    let row = data[i];
    scrape(row.url).then(adInfo => {
      //console.log(adInfo);
      let columns = {
        uuid: adInfo.adId
      };
      db.query(statement, columns, function(error) {
        if (error) throw error;
      });
    });
  }
  db.end();
}

Cannot enqueue Query after invoking quit.

Telenoobies
  • 938
  • 3
  • 16
  • 33

1 Answers1

0

You aren't awaiting anything. Should be something like this:

async function processData(err, data) {
  if (err) {
    throw err;
  }
  let db = mysql.createConnection({ ... });

  let statement = "INSERT INTO Kijiji SET ?";
  await db.connect();
  for (let i = 0; i < data.length; i++) {
    let row = data[i];
    const adInfo = await scrape(row.url);
    
    let columns = {
      uuid: adInfo.adId
    };
    
    await db.query(statement, columns)
  }
  db.end();
}

Or try it in parallel:

async function processData(err, data) {
  if (err) {
    throw err;
  }
  let db = mysql.createConnection({ ... });

  let statement = "INSERT INTO Kijiji SET ?";
  await db.connect();
  
  await Promise.all(data.map(async row => {
    const adInfo = await scrape(row.url);
    
    let columns = {
      uuid: adInfo.adId
    };
    
    await db.query(statement, columns)
  }));
  
  db.end();
}
zero298
  • 25,467
  • 10
  • 75
  • 100