我将 Mongoose 与 Node.js 结合使用,并具有以下代码,这些代码将在所有 save() 调用完成后调用回调。但是,我觉得这是一种非常肮脏的做法,希望看到完成这项工作的正确方法。
function setup(callback) {
// Clear the DB and load fixtures
Account.remove({}, addFixtureData);
function addFixtureData() {
// Load the fixtures
fs.readFile('./fixtures/account.json', 'utf8', function(err, data) {
if (err) { throw err; }
var jsonData = JSON.parse(data);
var count = 0;
jsonData.forEach(function(json) {
count++;
var account = new Account(json);
account.save(function(err) {
if (err) { throw err; }
if (--count == 0 && callback) callback();
});
});
});
}
}
最佳答案
您可以使用像 async 这样的库稍微清理一下代码。或 Step .
此外,我已经编写了一个小模块来为您处理加载夹具,因此您只需执行以下操作:
var fixtures = require('./mongoose-fixtures');
fixtures.load('./fixtures/account.json', function(err) {
//Fixtures loaded, you're ready to go
};
Github: https://github.com/powmedia/mongoose-fixtures
它还会加载夹具文件或对象的目录。
关于node.js - 如何等待所有异步调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673717/