2016-05-20 1 views
0

FirebirdからMongoDBに多くのレコードをコピーしようとしています。これは私の機能です。node.jsコールバックでの操作を遅らせる方法

var queue = 0; 
connection.sequentially(sql, (row) => { 
    queue++; 
    collection.insert(row, (err, result) => { 
     if (err) 
      return done(err); 
     queue--; 
     if (queue <= 0) 
      return done(null, result); 
    }); 
}, (err) => { 
    connection.detach(); 
    done(err); 
} 

私の問題はメモリです。書き込み操作は遅く、約100000回読み込んだ後はメモリがいっぱいです。キューの値があるレベル以下になるまで、次の読み込みを遅らせることは可能ですか?

答えて

0

これはasync.cargoを使用して、あなたを助けることができる多くのソリューションの一つであり、デモは、ワークフロー説明すべきである

// npm install async --save 
var async = require('async'); 

// your sql api, simple demo 
var collection = { 
    insert: function (row, cb) { 
     console.log('row inserted', row.name); 
     cb(null); 
    } 
}; 

// create a cargo object with 1 row payload 
// and extract cargo into worker variable 
var cargo = async.cargo(function (cargo_rows, callback) { 
    cargo_rows.forEach(function (row) { 
     console.log('processing: ' + row.name); 
     collection.insert(row, function(ciErr) { 
      if(ciErr){ 
       callback(ciErr); 
      } 
     }); // add rows, probably need some error checks 
    }); 
    callback(); 
}, 1); // number of cargo rows to process, if 2 - 2 rows will be inserted before callback called 

// add some items 
var rows = [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }]; 
rows.forEach(function (row) { 
    cargo.push(row, function (err) { 
     if (err) { 
      console.log('error processing: ' + row.name, '\nExiting'); 
     } else { 
      console.log('finished processing: ' + row.name); 
     } 
    }); 
}); 

// Result 
// 
// processing: item1 
// row inserted item1 
// finished processing: item1 
// processing: item2 
// row inserted item2 
// finished processing: item2 
// processing: item3 
// row inserted item3 
// finished processing: item3 

そしてcargo_rowsの数が2の場合、結果は次のとおりです。だから、

// processing: item1 
// row inserted item1 
// processing: item2 
// row inserted item2 
// finished processing: item1 
// finished processing: item2 
// processing: item3 
// row inserted item3 
// finished processing: item3 

アイデア順番に行を追加することです、あなたのキューは良い解決策ではありません、あなたはより良い約束を頼りに、簡単に置く:

start processing row => // you can have some validations here 
process row =>   // some error checking/logging 
finish process row => // cleanup memory, indeed i don't think you gonna need it 
have other rows ? restart worker with new row : done; 
+0

1つの質問:100000レコードと10000の貨物ペイロードで試しました。処理されたすべてのレコードを見ることができますが、nodejsスクリプトは終了しません。私は貨物が新しい記録を待っていると思うが、私は何も持っていない。どこでどのように貨物を破壊することができますか? – Gabriel

+0

貨物の中に 'callback'を呼び出す必要があります。基本的にコールバックは、私のデモ 'callback();のように、行の挿入が行われたときに呼び出されます。 –

関連する問題