【发布时间】:2018-05-23 08:07:11
【问题描述】:
我有一个非常复杂的查询。在此之前还有其他几个查询,我不想关注,因为它有效。
我想要一个 Productcategory 的所有产品,其中有一个声明。从索赔开始。无法创建新的“.then()”,因为我需要相应产品中的声明 ID。
感谢您的各种帮助。
这是代码:
.then(claims => {
const uniqClaims = _.uniqBy(claims, 'OnId');
uniqClaims.forEach(claim => {
CatProduct.findAll({
where: {
ProductCategoryId: claim.OnId,
},
}).then(catproducts => {
const ProductId = _.map(catproducts, product => product.ProductId);
Product.findAll({
where: {
id: ProductId,
},
}).then(newProducts => {
console.log('newProducts');
const addProducts = newProducts.map(v => v.ClaimId = claim);
products.push(...addProducts);
});
});
});
console.log(products);
return res.status(200).json(products);
});
声明和产品之间没有直接但传递的关系,因此 {where: ClaimId: claimIds} 是不可能的,也是无意的。 我想在 newproduct-Object 中有声明 ID。有什么想法吗?
非常感谢! 劳伦斯
更新 我现在将其更改为以下内容:
.then(uniqClaims => {
const claimIds = uniqClaims.map(claim => claim.OnId);
let products = [];
claimIds.foreach(claimId => {
CatProduct.findAll({
where: {
ProductCategoryId: claimId,
}
}).then(catproducts => {
const ProductIds = _.map(catproducts, product => product.ProductId);
Product.findAll({
where: {
id: ProductIds,
}, raw: true
}).then(newProducts => {
const serializedNewProducts = newProducts;
const newProductsWithClaims = serializedNewProducts.map(v => {
v.claim = claimId;
return v;
});
products.push(...newProductsWithClaims);
});
});
};
res.status(200).json(products);
});
“当然”它不起作用,因为 foreach 不是异步的。我怎样才能使它异步。我尝试了很多,包括回顾 Promises、异步等,但它只是不起作用。有人可以在这里写下正确的代码吗?我真的被困在这里了。
【问题讨论】:
标签: javascript node.js sequelize.js