如何创buildcallback后保存对象的数组?

假设我有以下function:

exports.addnames = function(req, res) { var names = ["Kelley", "Amy", "Mark"]; for(var i = 0; i < names.length; i++) { (function (name_now) { Person.findOne({ name: name_now}, function(err, doc) { if(!err && !doc) { var personDoc = new PersonDoc(); personDoc.name = name_now; console.log(personDoc.name); personDoc.save(function(err) {}); } else if(!err) { console.log("Person is in the system"); } else { console.log("ERROR: " + err); } } ); )(names[i]); } 

我的问题是我保存了名字后,我想返回结果:

 Person.find({}, function(err, doc) { res.json(200, doc); }) 

虽然我有一个名称callback,但似乎在保存所有名称的调用完成之前,最后一块代码(Persons.find({}))被执行了…因此,当用户转到浏览器,“doc”是空的…有什么办法可以确保在for循环完成后调用Persons.find({})?

最简单的方法就是使用asynchronous库,如https://github.com/caolan/async中提供的恰当命名的asynchronous库&#x3002;

如果您有一个要保存的名称列表,然后在完成时返回,那么它将如下所示:

 // save each of the names asynchronously async.forEach(names, function(name, done) { Person.findOne({name: name}, function(err, doc) { // return immediately if there was an error if(err) return done(err); // save the person if it doesn't already exist if(!doc) { var personDoc = new PersonDoc(); personDoc.name = name; console.log(personDoc.name); // the async call is complete after the save completes return personDoc.save(done); } // or if the name is already there, just return successfully console.log("Person is in the system"); done(); } ); }, // this function is called after all of the names have been saved // or as soon as an error occurs function(err) { if(err) return console.log('ERROR: ' + err); Person.find({}, function(err, doc) { res.json(200, doc); }) });