Midhunsai Midhunsai - 27 days ago 10
Javascript Question

how to return a Promise.all().then to a function

I am trying to return a

Promise.all()
to a function. I tried different ways but it is showing errors

here is my code



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

Answer
return Promise.all(array).then(resultantCount =>{
    console.log(JSON.stringify(resultantCount )); // resultanCout printing here
    return resultantCount;
});

This part of the code returns a Promise object. So you have to use .then() again in your countByTitle function.

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