gpt4 book ai didi

node.js - 如何创建回调后保存对象数组?

转载 作者:可可西里 更新时间:2023-11-01 10:44:34 25 4
gpt4 key购买 nike

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

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({})?

最佳答案

做这样的事情最简单的方法是使用一个异步库,比如恰当命名的 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);
})

});

关于node.js - 如何创建回调后保存对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12591791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com