Node js嵌套Promise.all错误

时间:2018-07-12 06:01:19

标签: javascript node.js promise es6-promise

exports.AllDataCounts= function(req, res) {
  var UserId = req.params.User_Id;
  Promise.all([
           Model.SchemaOne.count({ User_Id: UserId }).exec(),
           Model.SchemaTwo.find({ User_Id: UserId }).exec()
  ]).then(response_One => {
     console.log('response_One Success');
     var _ids = response_One[1].map(x => x._id );

     const GetMoreInfo = _id => {
             Promise.all([
                  Model.Cube_SchemaThree.count({ Cube_Id: _id }).exec(),
                  Model.Cube_SchemaFour.count({ Cube_Id: _id }).exec(),
             ]).then( response_three => {
                 console.log('response_three Success');
                 return response_three ;
              }).catch(error_3 => {
                 console.log('error');
                 return Cube_Id;
               });  
     };
     Promise.all(
           _ids.map(_id=> GetMoreInfo(_id))
     ).then(response_two => {
        console.log('response_two Success'); 
        res.send({ Status:true, Response: { Output1: response_One, Output3: response_two });
     }).catch( error_two = > {
        res.send({ Status: false, Error: error_two, Message: 'Some Error Occurred' });
     });
  }).catch( error_one = > {
     res.send({ Status: false, Error: error_1, Message: 'Some Error Occurred' });
  });
};

我希望控制台输出为

  

response_One Success

     

response_three成功

     

response_Two成功

但我得到的结果是

  

response_One Success

     

response_Two成功

     

response_Three Success

如果我将删除Promise中的GetMoreInfo函数,那么它将正常工作

1 个答案:

答案 0 :(得分:4)

您有:

const GetMoreInfo= _id => {
  Promise.all([
    Model.Cube_SchemaThree.count({ Cube_Id: _id }).exec(),
    Model.Cube_SchemaFour.count({ Cube_Id: _id }).exec(),
  ]).then( 

getMoreInfo不会返回其Promise.all,因此在您致电时未正确包含在较大的Promise链中

Promise.all(
  _ids.map(_id=> GetMoreInfo(_id))
).then( ...

(相反,目前.then会立即解决,因为正在Promise.all数组上调用undefined,这不是您想要的)

更改为:

const GetMoreInfo= _id => {
  return Promise.all([
    // ...