使用 async-await 后,我收到以下控制台日志。我不确定我做错了什么。
[
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 的数组
[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
所以我使用 setTimeout 来获得已解决的 promise 。
代码如下:
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);
});
我的代码中有什么错误,我得到的是 promise 数组而不是对象数组?
请帮忙。
最佳答案
async function getValue(x) {
await new Promise(r => setTimeout(r, 100)); // wait 100 ms
return x * 2;
}
const promises = [];
promises.push(getValue(1));
promises.push(getValue(2));
promises.push(getValue(3));
// right now, promises is an array of promises -- let's turn that into values:
(async () => {
const promiseValues = await Promise.all(promises);
console.log('values:');
console.log(promiseValues);
})();
这就是如何使用 Promise.all 将 Promise 数组转换为值数组
关于javascript - 将带有 Promise 的对象数组转换为普通数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64319107/