我正在尝试将 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
};
});
}
最佳答案
return Promise.all(array).then(resultantCount =>{
console.log(JSON.stringify(resultantCount )); // resultanCout printing here
return resultantCount;
});
这部分代码返回一个 Promise 对象。因此,您必须在 countByTitle
函数中再次使用 .then()
。
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));
});
}
关于javascript - 如何将 Promise.all().then 返回给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435653/