本文介绍了如何等待所有异步调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将Mongoose与Node.js结合使用,并具有以下代码,这些代码将在所有save()调用完成后调用回调.但是,我认为这是一种非常肮脏的方式,并且希望了解完成此操作的正确方法.
I'm using Mongoose with Node.js and have the following code that will call the callback after all the save() calls has finished. However, I feel that this is a very dirty way of doing it and would like to see the proper way to get this done.
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(); }); }); }); } }推荐答案
您可以使用异步或步骤.
此外,我已经编写了一个小模块,可以为您处理装载夹具,因此您只需执行以下操作:
Also, I've written a small module that handles loading fixtures for you, so you just do:
var fixtures = require('./mongoose-fixtures'); fixtures.load('./fixtures/account.json', function(err) { //Fixtures loaded, you're ready to go };Github: github/powmedia/mongoose-fixtures
它还将加载灯具文件或对象的目录.
It will also load a directory of fixture files, or objects.
更多推荐
如何等待所有异步调用完成
发布评论