2

假设我在函数中有以下内容:

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);
})

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

4

1 回答 1

1

做这样的事情最简单的方法是使用一个像恰当命名的异步库async,可以在https://github.com/caolan/async找到。

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

// 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);
    })

});
于 2012-09-25T22:17:18.963 回答