Вы правы, что Array.prototype.forEach
не ждет. Вместо этого вы должны использовать Array.prototype.map
и Promise.all
ShoppingCart.find({
"userId": id
}).then(async cart => {
let distinctTypes = cart[0].productsCart;
distinctTypes.sort(function(r, u) {
return r.manufacturerId > u.manufacturerId ? 1 : r.manufacturerId < u.manufacturerId ? -1 : 0
});
const distinctTypesWithProducts = await Promise.all(
distinctTypes.map(async function(thisType) {
let id = thisType.productId;
const product = await Product.findById(id)
thisType.product = product // changed assignment of product to thisType.product
return thisType
});
);
return distinctTypesWithProducts;
});
. Вы можете упростить приведенное выше с помощью проекта , который я начал. Взносы приветствуются.
const { pipe, assign, map, get } = require('rubico')
// userId => cart
const findCartByUserID = userId => ShoppingCart.find({ userId })
// [distinctType] => [distinctType] sorted
const sortDistinctTypes = distinctTypes => distinctTypes.sort((r, u) => {
return r.manufacturerId > u.manufacturerId ? 1 : r.manufacturerId < u.manufacturerId ? -1 : 0
})
// distinctType => distinctTypeWithProduct
const assignProduct = assign({
product: pipe([
get('productId'), // distinctType => productId
Product.findById, // productId => product
]), // distinctType.product = product; return distinctType
})
// userId => [distinctTypeWithProduct, distinctTypeWithProduct, ...]
const getDistinctTypesWithProductFromUserID = pipe([
findCartByUserID,
// userId => cart
get([0, 'productsCart']),
// cart => distinctTypes
sortDistinctTypes,
// distinctTypes => sortedDistinctTypes
map(assignProduct),
// sortedDistinctTypes => [distinctTypeWithProduct, distinctTypeWithProduct, ...]
])
getDistinctTypesWithProductFromUserID(id)