2013-01-22 21 views
1

我想知道如何處理在使用Node.js的異步庫的依賴,看看下面的例子:節點JS異步模塊系列依賴

db.open(function(error, client) { 
    client.collection(('my-collection', function(error, collection) { 
    collection.insert({ "email": "[email protected]" }, function(error, docs) { 
     // Do stuff. 
    }); 
    }); 
}); 

使用async library

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. 
}); 
+0

哇,從來沒見過這麼多過於複雜的函數表達式:'函數(回調){db.open(功能(error,client){callback(error,client);}); }'等於'function(callback){db.open(callback); }'等於'db.open'(也許是'db.open.bind(db)') – Bergi

回答

4

您正在使用async parallell,它可以一起運行所有功能,並且可以按任意順序完成。

你可以使用異步瀑布功能,從一個回調傳遞變量到下一個函數,例如。

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'  
}); 

或者你可以使用自動功能,它允許你指定哪些其他功能必須先完成例如。

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. 
}); 

Have a look at this to see all the available functions and their uses