Javascript 将具有Promise的对象数组转换为普通数组
在使用async Wait之后,我得到以下控制台日志。我不确定我做错了什么Javascript 将具有Promise的对象数组转换为普通数组,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,在使用async Wait之后,我得到以下控制台日志。我不确定我做错了什么 [ Promise { { categoryName: 'Salary', categoryAmount: '35000', categoryValue: 'salary', categoryId: '5f81c02c8e9fdf62f0422c09' } }, Promise { { categoryName: 'Custo
[
Promise {
{
categoryName: 'Salary',
categoryAmount: '35000',
categoryValue: 'salary',
categoryId: '5f81c02c8e9fdf62f0422c09'
}
},
Promise {
{
categoryName: 'Custom Category',
categoryAmount: '70000',
categoryValue: 'custom-category',
categoryId: '5f841d47f4aaf1462cb6065f'
}
}
]
如何将其转换为普通对象数组
像这样:
[
{
categoryName: 'Salary',
categoryAmount: '35000',
categoryValue: 'salary',
categoryId: '5f81c02c8e9fdf62f0422c09',
},
{
categoryName: 'Custom Category',
categoryAmount: '70000',
categoryValue: 'custom-category',
categoryId: '5f841d47f4aaf1462cb6065f',
},
];
我得到了一个数组,里面有未兑现的承诺
[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
在我的代码中,我得到的是承诺数组而不是对象数组,这是什么错误
请帮忙。
异步函数getValue(x){
等待新承诺(r=>setTimeout(r,100));//等待100毫秒
返回x*2;
}
常量承诺=[];
promises.push(getValue(1));
promises.push(getValue(2));
promises.push(getValue(3));
//现在,承诺是一系列承诺——让我们将其转化为价值观:
(异步()=>{
const promiseValues=等待承诺。全部(承诺);
log('value:');
console.log(承诺值);
})();代码>如果你有一个承诺数组,你可以通过
const resolvedValue=Promise.all(promises)获得它们的解析值数组代码>
exports.createBudget = async (req, res) => {
//RevenueCategories
const revenueData = await req.body.revenueCategories.map(async (el) => {
//Check if Revenue exists in Revenue Model's Collection, if true get it's _id
let currentDoc = await Revenue.findOne({
categoryValue: el.categoryValue,
}).select('_id');
//if we have _id then assign it to categoryId property
if (currentDoc !== null) {
el.categoryId = await (currentDoc._id + '');
}
//if new Revenue Category then create new Doc and assign it's _id to categoryId property
else if (currentDoc === null) {
let newCategData = {
categoryName: el.categoryName,
categoryValue: el.categoryValue,
};
let newCateg = await Revenue.create(newCategData);
el.categoryId = await (newCateg._id + '');
}
return el;
});
setTimeout(async () => {
console.log('Revenue Data', revenueData);
const budgetDoc = {
...req.body.budgetData,
revenueData,
};
const budget = await Budget.create(budgetDoc);
res.status(201).json({
data: {
status: 'success',
budget,
},
});
}, 5000);
});