【问题标题】:how to make a while loop in nodejs to be a series如何使nodejs中的while循环成为一个系列
【发布时间】:2015-08-05 13:56:09
【问题描述】:

我的 Nodejs 代码:

我正在尝试从服务器下载文件 (excel) 并解析这些 excel 文件,然后从该数据中仅将所需的数据存储到 mysql 数据库中,我可能会下载多个文件,因为我的循环可能会被中断,所以如何执行下面的代码以一系列同步方式运行

var r=0;        
if (issue.fields.attachment != '') {
          while (typeof issue.fields.attachment[r] != "undefined") {
            if (typeof issue.fields.attachment[r].content != "undefined") {
              var url = issue.fields.attachment[r].content;
              request({ 
                        method: "GET", 
                        "url": url, 
                        "headers": { "Content-Type": "application/json", }

    }, function(err, data, body) {

                  console.log('file downloading');

              }).pipe(fs.createWriteStream('file.xlsx'));

              console.log('file downloaded');

              parseXlsx('file.xlsx', function(err, data) {
                var i, j, k = 1, l = 0, m = 0, n = 0;


                console.log('parseXlsx cmpleted');

                while (data[i] != undefined) {

                  if (data[i][j] != '' || data[i][k] != '' || data[i][l] != '') {
                    var query = connection.query('insert into IP values ("' + data[i][j] + '","' + data[i][k] + '","' + data[i][l] + '","' + data[i][m] + '")',

                      function(error, results, fields) {

                      });
                  }

                  i++;
                }
              });

              r++;
              console.log('rvalue' + r);

            }
          }
        }

【问题讨论】:

  • 这个问题归结为“如何在 node.js 中对异步操作进行排序”?每天会多次询问此问题。我会尝试找到一个副本。
  • 您的第一个问题是您的代码根本不可读。使用单独的、不同的函数——你上面的函数做了一百万件事。如果您将自己限制为每个函数的一个目标,那么您的代码对您和其他人都会更有意义。
  • r 最初来自哪里?
  • 对于依赖顺序操作如此复杂的事情,您将需要使用 Promise。
  • r 最初是零启动

标签: mysql node.js excel promise synchronous


【解决方案1】:

我(很快,所以它可能有错误)使用async.forEachOfSeries 重写了这个来遍历你的附件。我使用async.forEachOf 进行数据库写入,因为我认为它们不需要串联。

var async = require('async');
if (issue.fields.attachment != '') {
    async.forEachOfSeries(issue.fields.attachment,function(attachment,r,callback){
        if (typeof issue.fields.attachment[r].content != "undefined") {
            var url = issue.fields.attachment[r].content;
            var ws = fs.createWriteStream('file.xlsx');
            request({ method: "GET", "url": url, "headers": { "Content-Type": "application/json" }
            }, function(err, data, body) {
                console.log('file downloading');
            }).pipe(ws);
            ws.on('finish',function() {
                console.log('file downloaded');
                parseXlsx('file.xlsx', function (err, data) {
                    var i, j, k = 1, l = 0, m = 0, n = 0;
                    for (i = 0; i < 15; i++) {
                        for (j = 0; j < 15; j++) {
                            if (regex.test(data[i][j])) {
                                k = 0;
                                break;
                            }
                        }
                        if (k == 0)
                            break;
                    }
                    for (k = 0; k < 15; k++) {
                        if (regex1.test(data[i][k])) {
                            break;
                        }
                    }
                    for (l = 0; l < 15; l++) {
                        if (regex2.test(data[i][l])) {
                            break;
                        }
                    }
                    for (m = 0; m < 15; m++) {
                        if (regex2.test(data[i][m])) {
                            break;
                        }
                    }
                    i = i + 1;
                    console.log('parseXlsx completed');
                    async.forEachOf(data,function(row,i,_callback){
                        if(i===0)return _callback();
                        if (data[i][j] != '' || data[i][k] != '' || data[i][l] != '') {
                            var query = connection.query('insert into IP values ("' + data[i][j] + '","' + data[i][k] + '","' + data[i][l] + '","' + data[i][m] + '")',
                                function (error, results, fields) {
                                    if(error){
                                        //Decide if you want to stop writing rows if one insert fails, if so uncomment next line
                                        //return _callback(error);
                                    }
                                    return _callback();
                                });
                        }
                    },function(err){
                        if(err){
                            //decide if you want to stop the whole process if the database errored, if so, uncomment next line
                            //return callback(err);
                        }
                        callback();
                    });
                });
            });
            ws.on('error',function(err) {
                //There was an error writing the file to disk, but I assume you want to continue anyway so I'm calling callback()
                //If you want to stop processing, call callback(new Error('Failed writing to disk'));
                return callback();
            });
        }
    });
}

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 2019-03-23
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多