I am learning node.js based on PHP background with a limited level of JavaScript. I think that now I have moved on to a change in thinking, which is implied by an asynchronous approach. And I like it.
But, like many others in front of me, I quickly understood the specific meaning of the "pyramid of death."
Therefore, I am building these little 'dummy' routes and views to understand how to use Async.js correctly. I just spent the last 5 hours writing the following code (rewritten, of course, dozens of times). It works, but I wonder how I could go further and make this code simpler (less verbose, easier to read and maintain).
I found many resources on the Internet and especially here, but always on pieces of information here and there.
I assume that at this point I should use "bind" and "this" with async.apply to shorten the last two functions, called a waterfall.
The problem is to define the db object so that I can use the collection method on it (for the second function).
I really searched for an example on Google, but it is surprising that you are not getting simple examples looking for "binding of an asynchronous waterfall" (as well as the many keyword variations I tried). Of course, there are answers, but none of them are suitable for this particular problem ... ore, quite possibly, I did not understand them.
Can someone help me? I'll be very grateful.
app.get('/dummy', function(req, res) { var MongoClient = require('mongodb').MongoClient; async.waterfall( [ async.apply(MongoClient.connect, 'mongodb://localhost:27017/mybdd'), function(db, callback) { db.collection('myCollection', callback); }, function(collection, callback) { collection.find().sort({"key":-1}).limit(10).toArray(callback); } ], function(err, results) { if (err) console.log('Error :', err); else { res.render('dummy.jade', { title:'dummy', results: results} ); } } ); } );