gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:54:36 24 4
gpt4 key购买 nike

我正在尝试将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com