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

时间:2021-07-12 10:48:40

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.

所以我需要在verifyDataInFile执行之前以某种方式在我的“readDataBase”函数中完成我的for循环。我正在编写节点js并从MySQL数据库获取数据。我没有运气任何提供任何“睡眠”功能的软件包,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");
        }
    })
}

1 个解决方案

#1


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:

与此同时,您仍然可以利用MySQL库在'result'事件上将写入流返回到您的文件的能力。优点是,当您听到DB的“结束”事件时,您将知道自己已完成,然后可以继续进行验证:

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中使用带节点的流

#1


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:

与此同时,您仍然可以利用MySQL库在'result'事件上将写入流返回到您的文件的能力。优点是,当您听到DB的“结束”事件时,您将知道自己已完成,然后可以继续进行验证:

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中使用带节点的流