如何重复执行nodejs mysql查询直到期望的结果出来?

eagi6jfj  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(438)
conn.connect(function (err) {
        if (err) throw err;
        var prizeCode = generatePrizeCode();// this method return a 5-digit code
        var query = "SELECT * FROM user WHERE code = ? ";
        var values = [[prizeCode]];
        conn.query(query, [values], function (err, result) {
            if (err) throw err;
            // Here I want to re-execute the above query if the result is not empty 
        });
    });

在上面的代码中,只要结果包含数据,我就希望执行query。但我不能像跟随伪码那样使用循环,

// if the result is empty, the generated code does not exist in database. So it can be used.
while(result.length != 0){
    var result = conn.query("SELECT * FROM user WHERE code = abc");
}

我怎样才能做到这一点?

cpjpxq1n

cpjpxq1n1#

基本上,您需要使用async\await或promises(基本相同)。https://javascript.info/async-awaithttpshttp://developer.mozilla.org/en-us/docs/web/javascript/reference/global\u objects/promise
这样,只有当你得到正确的结果时,你才能回来。

gv8xihay

gv8xihay2#

var mysql = require('mysql');
var pool  = mysql.createPool({
  host     : 'YOUR_HOST_NAME',
  user     : 'YOUR_USER_NAME',
  password : 'YOUR_PASSWORD',
  database : 'YOUR_DATABASE'
});

pool.getConnection(function(err, connection) {
  // connected! (unless `err` is set)
});

connection = mysql.createPool
var retryLimit=0;

var getData = function () {
if(retryLimit <= 50)
{
retryLimit++;
connection.query('SELECT * FROM user WHERE code = abc', function (error, results, fields) {
  if (error) {throw error;}
  else if(result.length <1) {
getData();
//call the same method again.
}
});
}
}

getData();

你可以添加else语句,做任何你想做的事情。

nr9pn0ug

nr9pn0ug3#

您必须使用回调或promises/async函数。下面是使用回调编写的方法:

const mysql = require('mysql');

const retryLimit = 50;

const connection = mysql.createConnection({
  database: 'test',
  host: 'localhost',
  password: 'hunter2',
  user: 'dave',
});

function getData(attempts, cb) {
  if (attempts < retryLimit) { // we haven't exausted our attempts yet
    const code = generatePrizeCode();
    connection.query('SELECT * FROM user WHERE code = ?', code, (err, result) => {
      if (err) {
        return cb(err);
      }
      if (result.length > 0) { // code already exists
        getData(attempts + 1, cb); // recurse
      } else { // this is a new code
        cb(null, code); // return the new code via the callback function
      }
    });
  } else { // we have exausted our attempts
    return cb(new Error('retry limit exceeded'));
  }
}

getData(0, (err, code) => {
  // do what you want here, e.g., console.log(code)
  connection.end();
});

请注意,如果递归次数过多并超过最大调用堆栈,这可能会导致节点崩溃。一种解决方法是调用setimmediate或settimeout,而不是直接递归。而不是线

getData(attempts + 1, cb); // recurse

使用

setImmediate(() => {
  getData(attempts + 1, cb); // recurse
});

// recurse, using setImmediate every 1000th time
if (attempts % 1000 === 0) {
  setImmediate(() => {
    getData(attempts + 1, cb); // recurse
  });
} else {
  getData(attempts + 1, cb); // recurse
}

使用promises和async/await样式会使这个问题得到很大的解决,可能看起来更像您习惯的样子(注意,这使用了 promise-mysql 图书馆):

const mysql = require('promise-mysql');

async function getData(connection) {
  const retryLimit = 50;
  for (let i = 0; i < retryLimit; i++) {
    const code = generatePrizeCode();
    const result = await connection.query('SELECT * FROM user WHERE code = ?', code);
    if (result.length === 0) { // this code doesn't exist yet
      return code;
    }
  }
  throw new Error('retry limit exceeded');
}

(async () => {
  try {
    const connection = await mysql.createConnection({
      database: 'test',
      host: 'localhost',
      password: 'hunter2',
      user: 'dave',
    });
    try {
      const code = await getData(connection);
      // do what you want here, e.g., console.log(code)
    } finally {
      connection.end();
    }
  } catch (err) {
    console.log(err);
  }
})();

相关问题