从循环nodejs

时间:2017-08-18 09:14:03

标签: javascript mysql node.js asynchronous

我是javascript和node js的新手。我实际上想根据MySQL值比较两个数据。

我想要做的是从data -> get数据对和db -> concat

value -> endloop值进行循环

这是我的代码

路由/ masterdata.js

var Masterdata = require('../models/Masterdata');
var outputFile = {}
for (var i = 0; i < dataFile.length; i++) {
  if (dataFile[i]['existing'] != null) {
    for (var x = 0; x < dataFile.length; x++) {
      var param = {
        tech_row: dataFile[i]['existing'],
        tech_col: dataFile[x]['new']
      };

      Masterdata.compareData(param, function(err, rows) {
        console.log(rows);
        outputFile.push({
          value: rows
        });
      });
    }
  }
}

console.log(outputFile);

模型/ Masterdata.js

var Masterdata = {
  compareData: function(param, callback) {
    return db.query('SELECT value FROM sod_matrix WHERE TECH_NAME_ROW = ? AND TECH_NAME_COL = ?', [param.tech_row, param.tech_col], callback);

  }
}

我的问题是如何将函数比较数据中的数据填充到循环中的数组中?

1 个答案:

答案 0 :(得分:0)

var Promise = require('bluebird');
var completed=[];
var Masterdata = require('../models/Masterdata');
var outputFile = []; //should be an array
for (var i = 0; i < dataFile.length; i++) {
  if (dataFile[i]['existing'] != null) {
    for (var x = 0; x < dataFile.length; x++) {
      var param = {
        tech_row: dataFile[i]['existing'],
        tech_col: dataFile[x]['new']
      };
      completed.push(new Promise(resolve, reject){
        Masterdata.compareData(param, function(err, rows) {
          if(err)
          {
            reject(err);
          }
          else
          {
            console.log(rows);
            outputFile.push(rows); //that;s pretty enough
            resolve();
          }
        });
      });
    }
  }
}
Promise.all(completed)
 .then((res)
 {
   console.log(outputFile);
 });