我使用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();
});
});
});
}
}
我使用['after'(HTTP://計算器。com/questions/6597493/synchronous-database-queries-with-node-js/6620091#6620091)功能。這樣簡單的實用功能可以幫助很多。 – Raynos
這就是開發者有時稱之爲[意大利麪代碼](http://en.wikipedia.org/wiki/Spaghetti_code)「。 [這是雅虎視頻教程](http://www.yuiblog.com/blog/2010/12/06/video-yuiconf2010-croucher/)解釋如何防止這種情況。我喜歡使用來自Caolan McMahon的幫助防止意大利麪代碼的庫,例如[異步](https://github.com/caolan/async)。可以在[this node_modules section](https://github.com/joyent/node/wiki/modules#async-flow))找到更多。 – Alfred