如何阻止我的代码异步运行?

时间:2017-10-10 17:47:28

标签: javascript mysql node.js

所以我需要在verifyDataInFile执行之前以某种方式在我的“readDataBase”函数中完成我的for循环。我正在编写节点js并从MySQL数据库获取数据。 我对任何提供任何“睡眠”功能的软件包没有任何好运,setTimeOut也不起作用,回调对我来说毫无意义。

任何帮助将不胜感激。

'use strict';

var mysql = require('mysql');
var fs = require('fs');
var wstream = fs.createWriteStream('Desktop\myOutput.txt');.


var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

  readDataBase();
  verifyDataInFile();
});

var readDataBase = function ()
{
    con.query("SELECT * FROM demo.users", function (err, rows, fields)
    {
        if (err) {
            return;
        } else {

            for (var i = 0; i < rows.length; i++)
            {
                wstream.write(rows[i].id + "   " + rows[i].firstName + " " + rows[i].lastName + "   " + rows[i].email + "\n" + "\n");
            }


        }

    });

}

var verifyDataInFile = function ()
{
    fs.readFile('Desktop\myOutput.txt', function (err, fs) {
        if (err) throw err;
        if (fs.indexOf('ut.cursus.luctus@utipsumac.org') >= 0) {
            console.log("something is here");
        } else {
            console.log("nope");
        }
    })
}

1 个答案:

答案 0 :(得分:0)

You have a few difficult things going on here, but the real difficulty is when writing to the stream in loop it's hard to know when all the writes are done. It's possible to pipe() directly from the DB to the file, but I don't have anything in front of me to test on, so I won't try a half-baked attempt at that, but it's worth investigating.

In the mean time, you can still take advantage of the MySQL library's ability to return a stream on write to your file on the 'result' event. The advantage is that you will know you are finished when you hear the DB's 'end' event and can then proceed with verify:

var query = con.query("SELECT * FROM demo.users")

query.on('error', function(err) {
    // Handle error, an 'end' event will be emitted after this as well
})

query.on('result', function(row){
    connection.pause();
    // pause so the db waits for the write to finish
    wstream.write(rows[i].id + " ...etc", function(){
        // write has finished…on to the next row
        connection.resume();
    });
})

query.on('end', function() {
    verifyDataInFile();
});

There's more about the MySQL stream api here: https://github.com/mysqljs/mysql#streaming-query-rows

And here's a different answer with an example of streaming directly to a file with the help of csv-transform: Using Streams in MySQL with Node