简体   繁体   中英

How can i stop my code from running asynchronously?

so i need to somehow make my for loop in my "readDataBase" function finish before the verifyDataInFile executes. i'm writing in node js and are getting data from an MySQL database. I haven't had any luck with any packages that provide any kind of "sleep" functions, setTimeOut doesn't work either, callbacks makes no sense to me.

any help would be greatly appreciated.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM