如何将 Promise.all().then 返回给函数

Mid*_*sai 2 javascript

我正在尝试将 a 返回Promise.all()到一个函数。我尝试了不同的方法,但它显示错误

这是我的代码

// All this iam doing in my server side controller
Promise = require('bluebird');

function countByTitle(accrdnArray) {
  console.log(accrdnArray) // array of objects is printing here
  var arrayCount = countfunc(accrdnArray);
  console.log(JSON.stringify(arrayCount)) // here it is not printing showing error 
}

function countfunc(accrdnArray) {
  var array = [];
  for (var i = 0; i < accrdnArray.lenght; i++) {
    var heading = accrdnArray[i].name;
    array.push(mongoCount(heading));
  }

  return Promise.all(array).then(resultantCount => {
      console.log(JSON.stringify(resultantCount)); // resultanCout printing here
      return resultantCount
    })
    // Here i want to return the resultantCount to above function.        
}

function mongoCount(heading) {
  var mongoQuery = {
    "ProCategory.title": heading
  }
  return Collection.count(mongoQuery).then(function(count) {
    return {
      name: categoryTitle,
      count: count
    };
  });
}
Run Code Online (Sandbox Code Playgroud)

Ven*_*pal 7

return Promise.all(array).then(resultantCount =>{
    console.log(JSON.stringify(resultantCount )); // resultanCout printing here
    return resultantCount;
});
Run Code Online (Sandbox Code Playgroud)

这部分代码返回一个 Promise 对象。所以你必须.then()在你的countByTitle函数中再次使用。

function countByTitle(accrdnArray) {
  console.log(accrdnArray) // array of objects is printing here
  var arrayCount = countfunc(accrdnArray);
  arrayCount.then(function(count) {
    console.log(JSON.stringify(count));
  });
}
Run Code Online (Sandbox Code Playgroud)