MySQL NodeJs - Proper way to get rows.each to work

拥有回忆 提交于 2019-12-13 03:25:37

问题


When I look for simple examples, everybody's style seems quite different. I'm tried 2 different styles, and got 2 different issues. In the code below, I have identified the source of the code and the error it gets in comments. I comment out or uncomment out each section and run separately, but each one has it's own errors. The "console.log(rows); " statement is showing the data, so the query itself is running and working.

// get the client
const mysql = require('mysql2');
const dashline = '---------------------------------';  

console.log (dashline); 
console.log ("Starting test"); 

// create the connection to database
const connection = mysql.createConnection({
  host: 'myhost',
  user: 'myuser',
  password: 'mypass',
  database: 'myDatabase'

});


console.log ("Got the database connection"); 


query = "select ID, user_nicename, user_email from wp_users where user_login = 'admin' limit 3 ";

console.log ("Starting query"); 

// Attempt 1
/*
connection.query(query, function(err, rows, fields){
  if (err) throw err;

  // from: https://html5hive.org/node-js-quickies-working-with-mysql/ 
  // error: SyntaxError: Unexpected token { (on the rows.each line below) 
  rows.each(element, index) {
    console.log(element.ID+ " " + element.user_nicename);
  }
  console.log (dashline); 
  console.log ("Query End"); 
  process.exit();   // Else Node hangs and must hit cntl-break to exit 

});
*/




// Attempt 2 

connection.query(query, function(err, rows, fields){
  if (err) throw err;
  console.log(rows); 
  // Roughly based on example on this page: 
  // https://datatables.net/reference/api/each()
  // TypeError: rows.each is not a function 
  rows.each( function(element, index) {
    console.log(element.ID + " " + element.user_nicename);
  });
  console.log (dashline); 
  console.log ("The end"); 
  process.exit();   // Else Node hangs and must hit cntl-break to exit 
});

回答1:


The method .each for Arrays doesn't exist, you should be using .forEach(function (element, index) {...}) instead




回答2:


Use the following:

  rows.forEach( function(element, index) {
    console.log(element.ID + " " + element.user_nicename);
  });

They are certainly similar, but there are differences. For example, "forEach" is an array method, but "$.each" can be used on any type of collection. And "forEach" is a built-in, whereas "$.each" requires loading the jQuery library.




回答3:


Got an answer here: [https://github.com/sidorares/node-mysql2/issues/999[1]. Problem with .forEach, .each or .map is that you are inside another function which is not an async function, meaning you cannot use "await" to call another async routine.

for (let r=0; r < rows.length; ++r) {
  console.log(rows[r].ID + " " + rows[r].user_nicename);
  await UpdatePassword(connection, rows[r].ID);
}

He also provided this alternative:

One "functional" way to iterate sequentially similar to map ( imo slightly less readable then for loop ):

await rows.reduce( async (previousPromise, row) => {
  await previousPromise;
  return UpdatePassword(row.ID);
}, Promise.resolve());


来源:https://stackoverflow.com/questions/57455356/mysql-nodejs-proper-way-to-get-rows-each-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!