node.js / postgres ...异步问题?

时间:2011-06-09 16:07:32

标签: postgresql node.js

我有一个类型列表:[“type1”,“type2”,type3“],我循环。对于每种类型:
     - 创建/执行查询以获取当前类型的项目
     - 当查询完成时运行另一个函数(on('end'))。

 for ( var i=0; i<types.length; i++ ){
    type = types[i];
    value = "test";
    ...

    // ADD ITEM: QUERY
    var query = client.query(...); // QUERY ITEMS OF A THE CURRENT TYPE

    // ADD ITEM: ERROR CHECKING
    query.on("error", function (err) {
      ...
    });

    with ({ t: type, v: value }) {  // I HAD TO DO THAT SO THAT ALL THE TYPES ARE TAKEN INTO ACCOUNT
      query.on('end', function() {
        my_function(t, v);
      });
    }
  }

my_function就像:

function my_function(type, value){
   console.log(type + ',' + value);  // CORRECT (I CAN SEE ALL THE TYPES BEEING LISTED)

   // QUERY OTHER STUFF BASED ON THE VALUE OF "type"
   var query = client.query(...);

   // MAIN STUFF
   query.on('row', function(row){
      console.log(type + ',' + value);  // THIS DOES NOT WORK ANYMORE... ONLY THE LAST TYPE IS TAKEN INTO ACCOUNT WHERE I EXPECT TO GET THIS MESSAGE FOR EACH TYPES.
     ...
   }

   // FINALIZE
   query.on('end', function(){
      ...
   }      
}

我想这与异步进程有关......但无法弄清楚错误的位置。

更新

我更新了我的循环,看起来像是:

 for ( var i=0; i<types.length; i++ ){
    type = types[i];
    value = "test";
    ...

    // ADD ITEM: QUERY
    var query = client.query(...); // QUERY ITEMS OF A THE CURRENT TYPE

    // ADD ITEM: ERROR CHECKING
    query.on("error", function (err) {
      ...
    });

    // MAIN STUFF GOES HERE
    (function(t, v) { query.on("end", function() {
      console.log(t + ',' + v); // OK, I CAN SEE THIS DISPLAYED FOR EACH TYPE
      my_function(t, v);
    }); })(type, value);
  }

我修改了my_function,看起来像是:

function my_function(type, value){
   console.log(type + ',' + value);  // OK, I CAN SEE THIS DISPLAYED FOR EACH TYPE

   // QUERY OTHER STUFF BASED ON THE VALUE OF "type"
   var query = client.query(...);

   // MAIN STUFF
   (function(t, v) {
     query.on("row", function(row) {
       console.log('TEST:' + t + ',' + v); // KO, I CAN ONLY SEE THIS DISPLAYED FOR ONE TYPE
   }); })(type, value);

   // FINALIZE
   query.on('end', function(){
      ...
   }      
}

1 个答案:

答案 0 :(得分:3)

with ({ t: type, v: value }) {  // I HAD TO DO THAT SO THAT ALL THE TYPES ARE TAKEN INTO ACCOUNT
      query.on('end', function() {
        my_function(t, v);
      });
    }

坏了。你想要的是这个

query.on("end", my_function.bind(null, type, value));

Function.prototype.bind允许您将参数绑定到函数。

永远不要使用with。另一种有效的方法是:

(function(t, v) {
  query.on("end", function() { my_function(t, v); });
})(type, value);