节点jsasynchronous模块系列依赖关系

我想知道如何处理在Node.js中使用asynchronous库的依赖关系,请看下面的例子:

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

使用asynchronous库 :

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

您正在使用asynchronous并行,它可以一起运行所有function,并可以按任意顺序完成。

你可以使用asynchronous瀑布函数,从一个callback传递variables到下一个函数。

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

或者你可以使用自动function,它允许你指定哪些其他function必须先完成例如。

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

看看这个,看看所有可用的function及其用途