1

Node.jsで非同期ライブラリを使用する際の依存関係を処理する方法を知りたいのですが、次の例を見てください。

db.open(function(error, client) {
  client.collection(('my-collection', function(error, collection) {
    collection.insert({ "email": "test@gmail.com" }, function(error, docs) {
      // Do stuff.
    });
  });
});

非同期ライブラリの使用:

async.parallel([
    function(callback) {
       db.open(function(error, client) {
         callback(error, client);
       });
    },
    function(callback) {
       // How do I access the "client" variable at this point?
    }
],
function(results){
   // Do stuff.
});
4

1 に答える 1

4

すべての関数を一緒に実行し、任意の順序で終了できる非同期並列を使用しています。

あるコールバックから次の関数に変数を渡す非同期ウォーターフォール関数を使用できます。

    async.waterfall([
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
   // result now equals 'done'    
});

または、auto関数を使用することもできます。これにより、他のどの関数を最初に終了する必要があるかを指定できます。

async.auto({
    get_data: function(callback){
        // async code to get some data
    },
    make_folder: function(callback){
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
    },
    write_file: ['get_data', 'make_folder', function(callback){
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, filename);
    }],
    email_link: ['write_file', function(callback, results){
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
    }]
});

だからあなたがあなたの場合にできることはこれです:

async.auto({
    dbReady: function(callback) {
       db.open(function(error, client) {
         callback(error, client);
       });
    },
    connected: ['dbReady', function(callback, results){
       // How do I access the "client" variable at this point?
       console.log(results.dbReady);
    }
},
function(results){
   // Do stuff.
});

利用可能なすべての機能とその使用法を確認するには、これをご覧ください

于 2013-01-22T21:41:53.237 に答える