简体   繁体   English

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

[英]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. 所以我需要以某种方式使我的“ readDataBase”函数中的for循环在verifyDataInFile执行之前完成。 i'm writing in node js and are getting data from an MySQL database. 我正在写节点js,并正在从MySQL数据库获取数据。 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. 提供任何类型的“睡眠”功能的程序包我都没有运气,setTimeOut也不起作用,回调对我来说毫无意义。

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. 可以直接从数据库通过pipe()传送到文件,但是我面前没有任何东西可以测试,因此我不会尝试半途而废,但是值得研究。

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. 同时,您仍然可以利用MySQL库在'result'事件中在写入文件时返回流的功能。 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 此处提供有关MySQL流api的更多信息: 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 这是一个不同的答案,并提供了一个通过csv-transform直接流式传输到文件的示例: 在MySQL中使用带有节点的流

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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