我有这个简单的 nodejs 应用程序,它为我的 Web 应用程序生成虚拟日期。它所做的只是:
- 删除虚拟数据库
- 填充库存集合
- 填充发票集合
- 填充 const 数据集合
当然,所有的动作都是异步的,我想一个接一个地顺序执行。对我来说,写一些东西来管理这种流更简单,但是,我想要一个主流的解决方案,它可以支持其他类型的流。例如,并行运行并在第一次失败时停止所有操作。
供您参考,请在骨架下方找到描述我的解决方案:
/*global require, console, process*/
var mongo, db, inventory, createChain;
function generateInventory(count) {
// returns the generated inventory
}
function generateInvoices(count, inventory) {
// returns the generated invoices
}
function generateConst() {
// returns the generated const data
}
mongo = require('mongojs');
db = mongo.connect('dummy', ['invoices', 'const', 'inventory']);
createChain = function () {
"use strict";
var chain = [false], i = 0;
return {
add: function (action, errMsg, resultCallback) {
chain[chain.length - 1] = {action: action, errMsg: errMsg, resultCallback: resultCallback};
chain.push(false);
return this;
},
invoke: function (exit) {
var str, that = this;
if (chain[i]) {
chain[i].action(function (err, o) {
if (err || !o) {
str = chain[i].errMsg;
if (err && err.message) {
str = str + ": " + err.message;
}
console.log(str);
} else {
if (chain[i].resultCallback) {
chain[i].resultCallback(o);
}
i += 1;
that.invoke(exit);
}
});
} else {
console.log("done.");
if (exit) {
process.exit();
}
}
}
};
};
createChain()
.add(function (callback) {
"use strict";
console.log("Dropping the dummy database.");
db.dropDatabase(callback);
}, "Failed to drop the dummy database")
.add(function (callback) {
"use strict";
console.log("Populating the inventory.");
db.inventory.insert(generateInventory(100), callback);
}, "Failed to populate the inventory collection", function (res) {
"use strict";
inventory = res;
})
.add(function (callback) {
"use strict";
console.log("Populating the invoices.");
db.invoices.insert(generateInvoices(10, inventory), callback);
}, "Failed to populate the invoices collection")
.add(function (callback) {
"use strict";
console.log("Populating the const.");
db["const"].insert(generateConst(), callback);
}, "Failed to populate the const collection")
.invoke(true);
谁能推荐一个相关的nodejs包,它也很容易使用?
非常感谢你。