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

时间:2019-01-05 09:05:39

标签: javascript mysql node.js database node-mysql

'c'

在上面的代码中,只要结果包含数据,我想执行查询。但是我不能像使用pseucode一样使用循环,

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

我该如何实现?

3 个答案:

答案 0 :(得分:0)

基本上,您将需要使用async \ await或promises(大致相同)。  https://javascript.info/async-await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

这样,您只有在获得正确结果后才能返回。

答案 1 :(得分:0)

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语句,然后执行您想做的任何事情。

答案 2 :(得分:0)

您将必须使用回调或promise / 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
}

使用promise和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);
  }
})();