nodejs中的同步循环

时间:2015-07-26 08:26:57

标签: node.js postgresql

//Importing: postges DB connection
var pg = require('pg');
var conString = "postgres://readxxx:p@ssword@vmwoxxx-tst:8888/worxxx";
var prvsiteid = '';
var cursiteid = '';
var qurystring = '';

pg.connect(conString, function(err, client, done) {
  if (err) {
    return console.error('error fetching client from pool', err);
    return;
  }
  
  client.query("select site_id,created_at,started_at,completed_at,notes,finish_code from _background_tasks where finish_code > 0 and site_id > 0 and abs(extract(Epoch from (now()::timestamp without time zone - completed_at)))/60 <= 4600 order by site_id asc", function(err, result1) {
    done();
    if (err) {
      return console.error('error running query', err);
      return;
    }
    for (var i = 0; i < result1.rowCount; i++) {
      cursiteid = result1.rows[i].site_id;
      if (prvsiteid != cursiteid) {
        prvsiteid = cursiteid;
        qurystring = "select trim(su.name) as name, case When trim(su.email) is null then su.name || '@netapp.com' when trim(su.email) > '' then su.name || '@netapp.com' else su.name end uemail,su.friendly_name as frdname from system_users su where su.state = 'active' and su.id in (select distinct(system_user_id) from users u where u.site_id = " + cursiteid + "and u.admin_level >= 5)"
        client.query(qurystring, function(err, result2) {
          done();
          if (err) {
            return console.error('error running query', err);
            return;
          }
          for (var j = 0; j < result2.rowCount; j++) {
            console.log(cursiteid, result2.rows[j].name, result2.rows[j].uemail, result2.rows[j].frdname);
          }
        });
      }
      console.log(result1.rows[i].site_id, result1.rows[i].created_at, result1.rows[i].started_at, result1.rows[i].completed_at);
    }
  });
});

我知道NodeJS程序是异步的,但这种情况我打算它是同步的。

for loop(外部) - &gt; for loop(inner)当外部forloop用新站点id更改时我想从内部循环向所有emailid发送电子邮件,并且还必须打印外部循环的每个站点的结果行。

1 个答案:

答案 0 :(得分:0)

  1. 如果您使用的库不支持同步操作,则无法在没有异常情况的情况下同步使用它(您希望在您的代码中使用异议。无论老板压力多大)。
  2. 您可以使用 Promises ,特别是 bluebird 来支持提供异步操作的循环和其他操作基于回调的异步函数,并将它们转换为Promise就绪函数。