gpt4 book ai didi

javascript - Node/Express - 如何等到 For 循环结束以 JSON 响应

转载 作者:行者123 更新时间:2023-12-02 18:07:55 26 4
gpt4 key购买 nike

我的 Express 应用程序中有一个函数,可以在 For 循环中进行多个查询,我需要设计一个回调,在循环完成时使用 JSON 进行响应。但是,我还不确定如何在 Node 中执行此操作。这是我到目前为止所拥有的,但它还没有工作......

exports.contacts_create = function(req, res) {
var contacts = req.body;
(function(res, contacts) {
for (var property in contacts) { // for each contact, save to db
if( !isNaN(property) ) {
contact = contacts[property];
var newContact = new Contact(contact);
newContact.user = req.user.id
newContact.save(function(err) {
if (err) { console.log(err) };
}); // .save
}; // if !isNAN
}; // for
self.response();
})(); // function
}; // contacts_create

exports.response = function(req, res, success) {
res.json('finished');
};

最佳答案

除了回调结构之外,您的代码还存在一些问题。

var contacts = req.body;
(function(res, contacts) {

...

})(); // function

^ 您正在参数列表中重新定义 contactsres,但没有传入任何参数,因此在函数内 res联系人将是未定义

此外,不确定您的 self 变量来自何处,但也许您在其他地方定义了该变量。

对于回调结构,您正在寻找类似的东西(假设联系人是一个数组):

exports.contacts_create = function(req, res) {
var contacts = req.body;

var iterator = function (i) {
if (i >= contacts.length) {
res.json('finished'); // or call self.response() or whatever
return;
}

contact = contacts[i];
var newContact = new Contact(contact);
newContact.user = req.user.id
newContact.save(function(err) {
if (err)
console.log(err); //if this is really a failure, you should call response here and return

iterator(i + 1); //re-call this function with the next index
});

};

iterator(0); //start the async "for" loop
};

但是,您可能需要考虑并行执行数据库保存。像这样的事情:

var savesPending = contacts.length;
var saveCallback = function (i, err) {
if (err)
console.log('Saving contact ' + i + ' failed.');

if (--savesPending === 0)
res.json('finished');
};

for (var i in contacts) {
...
newContact.save(saveCallback.bind(null, i));
}

这样您就不必等待每次保存完成后再开始下一次数据库往返。

如果您不熟悉我为什么使用 saveCallback.bind(null, i),基本上是为了让回调能够在发生错误时知道哪个联系人失败。请参阅Function.prototype.bind如果您需要引用。

关于javascript - Node/Express - 如何等到 For 循环结束以 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937889/

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