如何创建保存一组对象的回调帖子?

时间:2012-09-25 22:06:44

标签: node.js mongodb mongoose

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

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({}))在保存所有名称的调用完成之前执行...因此当用户进入浏览器中的url,“doc”为空...有什么方法可以确保在for循环完成后调用Persons.find({})?

1 个答案:

答案 0 :(得分:1)

执行此类操作的最简单方法是使用异常库,例如可在https://github.com/caolan/async找到的恰当名称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);
    })

});