我可以在async.js forEach中扩展迭代器的function吗?
我正在使用async.js在集合上运行for循环。 出于性能方面的原因,我想将一个数据库连接传递给迭代器方法,这样每次迭代器运行时都不会打开/closures数据库连接。 我正在为我的数据模型使用mongoose.js。
下面的代码获取所有的艺术家mongo,然后为每个添加一首歌曲。 我的问题是,我怎样才能使用addArtistSong updateAllArtists相同的数据库连接?
function updateAllArtists() { var db = mongoose.createConnection('localhost/dbname'); var Artist = db.model('Artist', artistSchema); Artist.find({}, function(err, artists) { // for each artist, add a song async.forEach(artists, addArtistSong, function(err) { }); } function addArtistSong(artist, cb) { // THIS IS WHERE I NEED A DB CONNECTION var Song = db.model('Song', songSchema); }
我能否以某种方式扩展迭代器签名,如addArtistSong(artist,db,cb)? 那么我怎样才能从forEach的电话里传递这个信息呢?
一个select是使数据库连接成为一个全局variables。 但是如果你不想要的话,你总是可以使用闭包来创build函数之间的共享variables:
(function(){ // create db in this closure var db = mongoose.createConnection('localhost/dbname'); function updateAllArtists() { // now db is available here var Artist = db.model('Artist', artistSchema); Artist.find({}, function(err, artists) { // for each artist, add a song async.forEach(artists, addArtistSong, function(err) {}); }); } function addArtistSong(artist, cb) { // and also available here var Song = db.model('Song', songSchema); } })()
另一种select是将其作为parameter passing给addArtistSong
。 由于async.forEach
期望迭代器函数只接受2个参数,我们可以使用匿名函数包装函数将3个parameter passing给addArtistSong
:
function addArtistSong(db,artist,callback) { db.model(); //... }
并在async.forEach
调用它:
async.forEach( artists, function(x,cb){addArtistSong(db,x,cb)}, function(err) {} );
- 有没有办法停止执行下一个与nodejsasynchronous系列function?
- NodeJS,asynchronousforEachSeries执行顺序
- 嵌套节点async.eachSeries
- nodejsasynchronous:多个相关的HTTP API调用
- Async.retry在等待间隔之前立即执行
- 在Node.js中使用MongoDB进行扩展,我应该什么时候一次查询所有的ID,并行查询每个ID?
- Nodejs / Async:如何在代码片段中提到的async.map的iteratee函数中如何工作?
- node.js中的async.js瀑布:如何使用bind和这个?
- asynchronous瀑布不正确保存与mongoose