简体   繁体   English

猫鼬的承诺不会将数据传递到下一个链

[英]Mongoose Promise not passing data to next chain

I am querying MongoDB using mongoose with promise. 我正在使用带有承诺的猫鼬查询MongoDB。 The result is accessible only in the first .then(function(results){ // can send the result from here..}) . 结果只能在第一个.then(function(results){ // can send the result from here..}) But when I manipulate the results and pass it to the next .then() chain it is not accessible. 但是,当我操纵结果并将其传递给下一个.then()链时,它是不可访问的。 Below is the full function. 以下是全部功能。

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));
}

Please let me know what I am doing wrong here..thanks 请让我知道我在做什么错..谢谢

Instead of 代替

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) 
  }
})

try 尝试

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;

Bottom line: don't use multiple returns per function (as in forEach ). 底线:不要对每个函数使用多个返回值(如forEach )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM