根据可用的数据ui应该得到2结果,但是因为我把res.send放入了循环所以只有1结果,所以它结束了,有人可以帮我吗……。
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
其外部。
为了解决这个问题,您可以使用async或promises。请参阅下面的使用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()
}
});
})
}
}
这是如何工作的,它创建了一个配置文件列表以查找并将其存储在中var profiles_to_get = []
。您使用的Promise.All(profiles_to_get)
可以让您在获取所有配置文件后执行操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句