1

我正在编写一些 PostgreSQL 事务,一旦执行了 forEach 中的每个函数,我就需要执行回调。这是一些代码:

var sql = "BEGIN;UPDATE object SET name = "+data.name+", object_subtype_id = "+data.object_subtype_id+" WHERE id = "+data.id+";";
db.driver.execQuery(sql, function(err, result) {
  data.object_subtype.object_property_type.forEach(function(item) {
    db.driver.execQuery("WITH upsert AS (UPDATE object_property SET value = '"+item.value+"' WHERE object_property_type_id = "+item.id+" AND object_id = "+data.id+" RETURNING *) INSERT INTO object_property (object_property_type_id, object_id, value) SELECT "+item.id+", "+data.id+", '"+item.value+"' WHERE NOT EXISTS (SELECT * FROM upsert);", function(err, nb) {
      // I need to send the COMMIT; here once all the functions in the forEach have been executed
    });
  });
});

我看过async但我不确定如何或者如果可以的话,将它应用于我的情况。

有什么想法吗?

谢谢!

4

2 回答 2

1

如果您不想使用异步(它有时会使简单的应用程序复杂化),JS 的做法是通过引用计数。做这个;

var sql = "BEGIN;UPDATE object SET name = "+data.name+", object_subtype_id = "+data.object_subtype_id+" WHERE id = "+data.id+";";
db.driver.execQuery(sql, function(err, result) {
  var counter =0;
  data.object_subtype.object_property_type.forEach(function(item) {
    db.driver.execQuery("WITH upsert AS (UPDATE object_property SET value = '"+item.value+"' WHERE object_property_type_id = "+item.id+" AND object_id = "+data.id+" RETURNING *) INSERT INTO object_property (object_property_type_id, object_id, value) SELECT "+item.id+", "+data.id+", '"+item.value+"' WHERE NOT EXISTS (SELECT * FROM upsert);", function(err, nb) {
      //THIS IS WHERE REFERENCE COUNTING HAPPENS
      counter++;
      if(counter === data.subtype.type.length) {
          COMMIT (since all callback functions returned
      }
      // I need to send the COMMIT; here once all the functions in the forEach have been executed
    });
  });
});
于 2013-08-20T02:32:21.030 回答
1

结合 async.series 和 async.each 你会得到这个漂亮的片段:

var sql = "BEGIN;UPDATE object SET name = "+data.name+", object_subtype_id = "+data.object_subtype_id+" WHERE id = "+data.id+";";

async.series([
  function (next) {
    db.driver.execQuery(sql, next);
  },
  function (next) {
    async.each(data.object_subtype.object_property_type, function (item, next) {
      db.driver.execQuery("WITH upsert AS (UPDATE object_property SET value = '"+item.value+"' WHERE object_property_type_id = "+item.id+" AND object_id = "+data.id+" RETURNING *) INSERT INTO object_property (object_property_type_id, object_id, value) SELECT "+item.id+", "+data.id+", '"+item.value+"' WHERE NOT EXISTS (SELECT * FROM upsert);", next);
    }, next);
  }
], function (err, results) {
  // Not sure what you want to do with the result
});

根据您想要的结果,它可能需要一些调整。

于 2013-08-19T19:39:59.007 回答