【发布时间】:2013-10-17 17:37:54
【问题描述】:
我正在尝试使用async 库,但我不知道如何在现实世界的示例中重写回调地狱。我对串联方法以及与某些现有驱动程序的通信特别感兴趣。有人可以使用 async.js 系列方法重写以下源代码吗?取自this link。
我不喜欢 MongoDb。如果有人将其他一些回调地狱示例改写为异步系列,那就太好了。
除了异步库之外,我还对任何替代解决方案感兴趣。但同样 - 在该解决方案中重写此示例(或显示其他完整示例),以便我们可以查看真实代码并进行比较。
var MongoClient = require('../lib/mongodb').MongoClient
, format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : 27017;
console.log("Connecting to " + host + ":" + port);
MongoClient.connect(format("mongodb://%s:%s/node-mongo-examples?w=1", host, port), function(err, db) {
db.dropDatabase(function(err, result) {
var collection = db.collection('test');
// Erase all records from the collection, if any
collection.remove({}, function(err, result) {
// Insert 3 records
for(var i = 0; i < 3; i++) {
collection.insert({'a':i}, {w:0});
}
collection.count(function(err, count) {
console.log("There are " + count + " records in the test collection. Here they are:");
collection.find().each(function(err, item) {
if(item != null) {
console.dir(item);
console.log("created at " + new Date(item._id.generationTime) + "\n")
}
// Null signifies end of iterator
if(item == null) {
// Destory the collection
collection.drop(function(err, collection) {
db.close();
});
}
});
});
});
});
});
【问题讨论】:
-
还可以查看
step和streamline.js了解更多想法。
标签: javascript node.js async.js