我使用承诺的mongoose查询MongoDB。结果只能在第一个.then(function(results){ // can send the result from here..})
中访问。但是当我操纵结果并将其传递给下一个.then()
链时,它无法访问。以下是完整的功能。
exports.getAcl = function(req, res) {
User.findAsync({}, {
acl: 1
})
.then(function(results){
var aclList = [];
results.forEach(function(result,index,arr){
aclList[result._id] = result;
if (index === (arr.length - 1)) {
console.log('I can log the aclList here..', aclList)
return aclList // But neither able to send it to next chain nor to front end res.send(aclList)
}
})
})
.then(function(aclList){
console.log(aclList) // Loging undefined
res.status(200).json(aclList); // undefined
})
.catch(handleError(res));
}
请让我知道我在这里做错了什么..谢谢
答案 0 :(得分:0)
而不是
results.forEach(function(result,index,arr){
aclList[result._id] = result;
if (index === (arr.length - 1)) {
console.log('I can log the aclList here..', aclList)
return aclList // But neither able to send it to next chain nor to front end res.send(aclList)
}
})
尝试
var resArray = [];
results.forEach(function(result,index){
aclList[result._id] = result;
if (index === (arr.length - 1)) {
newRes.push(aclList);
}
})
// console.log(resArray) to verify they are there
return resArray;
底线:不要为每个功能使用多个退货(如forEach
中所述)。