根据可用的数据,ui 应该得到 2 个结果,但只得到一个,因为我将 res.send 放入循环中,所以它即将结束,任何人都可以帮助我......
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
record.find(item).toArray((err, result) => {
if (err) {
return
}
if (result) {
for (var i in result) {
var id = result[i].recieved_id;
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
return
}
if (resp) {
console.log(resp);
} else {}
});
}
res.send(resp);
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
}
最佳答案
问题在于获取配置文件。您正在使用 mongodb 的 find,它是异步。因此,在您的 for
周期中,您开始获取配置文件,但随后在配置文件获取完成之前发送出 res.send
。
来自 profile.find(...
) 的回调将在 res.send
之后执行。除此之外,resp
变量位于 find 回调内部,而您正尝试将其 res.send
发送到外部。
要解决这个问题,您可以使用异步或 promise 。请参阅下面使用 Promise 的代码。
var Promise = require('bluebird')
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
record.find(item).toArray((err, result) => {
if (err) {
return
}
if (result) {
var profiles_to_get = []
var profiles = []
for (var i in result) {
var id = result[i].recieved_id;
profiles_to_get.push(get_profile(id, profiles))
}
Promise.all(profiles_to_get)
.then(() => {
res.send(profiles);
})
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
function get_profile (id, profiles) {
return new Promise(function (resolve, reject) {
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
reject(err)
return
}
if (resp) {
profiles.push(resp)
resolve()
} else {
reject()
}
});
})
}
}
其工作原理是,它创建一个配置文件列表以查找并将其存储在 varprofiles_to_get = []
中。您可以使用 Promise.All(profiles_to_get)
,它可以让您在获取所有配置文件后执行一些操作。
关于node.js - 如何在Node.js中执行for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39586504/